[Spring Boot] JdbcTemplate data connection template—Getting started with JdbcTemplate

Getting started with JdbcTemplate

This section starts from the basic part to introduce what is JDBC and what is JdbcTemplate, and then introduces how the Spring Boot project uses JdbcTemplate to operate the database.

1. Introduction to JdbcTemplate

1.1 What is JDBC

JDBC (Java Data Base Connectivity, Java Database Connectivity) is an API used in the Java language to standardize how applications access databases. It provides unified access methods for multiple relational databases, such as methods for querying and updating data in the database. JDBC provides a baseline against which more advanced tools and interfaces can be built, enabling database developers to write database applications.

1.2 What is JdbcTemplate

As an API specification for Java to access databases, JDBC unifies the access methods of various databases. However, using JDBC directly in Java programs is still very complicated and cumbersome. Therefore, Spring encapsulates JDBC in a deeper level, and JdbcTemplate is provided by Spring. Convenient tool for working with databases. It mainly implements the management of database connections. We can use JdbcTemplate to perform all database operations, such as queries, inserts, updates, deletes, etc., and effectively avoids the cumbersome coding caused by directly using JDBC.

As the master of Spring, Spring Boot will naturally integrate JdbcTemplate. Spring Boot provides a corresponding Starter for the use of JDBC: spring-boot-starter-jdbc, which is actually a further encapsulation of Spring JDBC to facilitate better use of JDBC in Spring Boot projects.

1.3 Features of JdbcTemplate

It is fast. Compared with ORM framework, JDBC method is the fastest.

The configuration is simple, and Spring encapsulates almost no additional configuration except the database connection.

Easy to use, it is more like the DBUtils tool class, just inject the JdbcTemplate object.

1.4 Several types of methods of JdbcTemplate

Although JdbcTemplate is simple, it is very powerful. It provides very rich and practical methods. In summary, there are mainly the following types of methods:

1) execute() method: can be used to execute any SQL statement, generally used to execute DDL statements.

2) update(), batchUpdate() methods: used to execute statements such as adding, modifying and deleting.

3) query() and queryForXXX() methods: used to execute query-related statements.

4) call() method: used to execute statements related to database stored procedures and functions.

In general, the three types of operations of adding, deleting, and modifying are mainly completed using the update() and batchUpdate() methods. The query() and queryForObject() methods are mainly used to complete the query function. The execute() method can be used to create, modify, and delete database tables. The call() method is used to call stored procedures.

In most cases, we will use a more powerful persistence framework to access the database, such as MyBatis, Hibernate or Spring Data JPA. The reason why I introduce a basic database framework like JdbcTemplate is just to hope that readers can start learning from the basics. Only by mastering these basic frameworks can we better learn other complex ones.

2.Spring Boot integrates JdbcTemplate

It is very simple to integrate JDBC with Spring Boot. You only need to introduce dependencies and perform basic configuration. Next, we will use a specific example to learn how to use Spring's JdbcTemplate to perform database operations.

Step 01 Add dependency configuration.

Add JDBC and other related dependencies in the pom.xml configuration file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

In the above example, the spring-boot-starterjdbc dependency is introduced in the pom.xml file. At the same time, since MySQL is used as the database in the project, the MySQL driver package needs to be introduced into the project. spring-boot-starter-jdbc directly depends on HikariCP and spring-jdbc.

  • HikariCP is the database connection pool used by Spring Boot 2.0 by default and is also the legendary fastest database connection pool.
  • spring-jdbc is a simple encapsulation of JDBC by the Spring framework, providing a development toolkit that simplifies JDBC operations.

Step 02 Create database and table structure.

First create the jdbctest test database, and then create the student table, including fields such as id, name, sex, age, etc. The corresponding SQL script is as follows:

DROP TABLE IF EXISTS 'student';
CREATE TABLE 'student' (
			'id' bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
			'name' varchar(32) DEFAULT NULL COMMENT '姓名',
			'sex' int DEFAULT NULL,
			'age' int DEFAULT NULL,
			PRIMARY KEY ('id')
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;;

Step 03 Configure the data source.

Configure MySQL database connection related content in application.properties. The specific configuration is as follows:

spring.datasource.url=jdbc:mysql://Localhost:3306/jdbctest?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

In the above example, the database connection configuration is very simple, including the database connection address, user name, password and data driver, and no other additional configuration is required. In Spring Boot 2.0, com.mysql.jdbc.Driver has been expired, and it is recommended to use com.mysql.cj.jdbc.Driver.

Step 04 Use JdbcTemplate.

JdbcTemplate has been integrated into the Spring Boot project and data has been created above. Next, create a unit test class JdbcTests to verify that JdbcTemplate operates the database. The sample code is as follows:

@RunWith(SpringRunner.class)
    @SpringBootTest
    class JdbcTests {
    
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Test
    void querytest() throws SOLException {
    
    
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from student");
        System.out.println(list.size());
        Assert.assertNotNull(list);
        Assert.assertEquals(1,list.size());
    }
}

The above is a test example simply using JdbcTemplate. Spring's JdbcTemplate is automatically configured. Use @Autowired to inject JdbcTemplate into the required Bean and call it directly.

The operation is successful. JdbcTemplate has connected to the database and successfully executed the data query operation. The above integrates JdbcTemplate into the Spring Boot project.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/132354902