Spring JdbcTemplate (detailed usage)

In enterprise-level application development, few people directly use the native JDBC API for development, because using the JDBC API to operate the database is very cumbersome. For example, we need to manually control the opening of the database connection, exception handling, transaction processing, and finally manual closing. The connection releases resources and so on.

Spring provides a Spring JDBC module, which encapsulates the JDBC API. Its main purpose is to reduce the difficulty of using the JDBC API and use the JDBC API in a more direct and concise way.
Using Spring JDBC, developers only need to define the necessary parameters and specify the SQL statements to be executed, and then they can easily perform JDBC programming and access the database.

Complex and tedious work such as driver loading, opening and closing of database connections, creation and execution of SQL statements, exception handling and transaction processing are all completed by Spring JDBC. Spring JDBC provides multiple practical database access tools to simplify JDBC development, among which JdbcTemplate is the most used.

JdbcTemplate

JdbcTemplate is the core class in the Spring JDBC core package (core). It can obtain database-related information through configuration files, annotations, Java configuration classes, etc., and realizes driver loading, connection opening and closing, and connection opening and closing during the JDBC development process. Encapsulation of SQL statement creation and execution, exception handling, transaction processing, data type conversion and other operations. We can easily perform JDBC programming by passing in SQL statements and necessary parameters.

The fully qualified name of JdbcTemplate is org.springframework.jdbc.core.JdbcTemplate, which provides a large number of methods for querying and updating the database, as shown in the following table.

method illustrate
public int update(String sql) Used to execute statements such as add, update, delete, etc.;
  • sql: SQL statement to be executed;
  • args represents the parameters that need to be passed into the SQL statement.
public int update(String sql,Object... args)
public void execute(String sql) Can execute any SQL, generally used to execute DDL statements;
  • sql: SQL statement to be executed;
  • action represents the function to be called after executing the SQL statement.
public T execute(String sql, PreparedStatementCallback action)
public <T> List<T> query(String sql, RowMapper<T> rowMapper, @Nullable Object... args) 
Used to execute query statements;
  • sql: SQL statement to be executed;
  • rowMapper: used to determine the type of returned collection (List);
  • args: Indicates the parameters that need to be passed into the SQL statement.
public <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args)
public int[] batchUpdate(String sql, List<Object[]> batchArgs, final int[] argTypes)  Used to execute add, update, delete and other statements in batches;
  • sql: SQL statement to be executed;
  • argTypes: JDBC types of SQL parameters that need to be injected;
  • batchArgs: Indicates the parameters that need to be passed into the SQL statement.

 Create a jdbc.properties in the src directory, and configure the database connection information in the configuration file.

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_jdbc_db
jdbc.username=root
jdbc.password=root

Create an XML configuration file Beans.xml in the src directory. The configuration content is as follows. 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启组件扫描-->
    <context:component-scan base-package="com.xiaorizi"></context:component-scan>
    <!--引入 jdbc.properties 中的配置-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--定义数据源 Bean-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!--数据库连接地址-->
        <property name="url" value="${jdbc.url}"/>
        <!--数据库的用户名-->
        <property name="username" value="${jdbc.username}"/>
        <!--数据库的密码-->
        <property name="password" value="${jdbc.password}"/>
        <!--数据库驱动-->
        <property name="driverClassName" value="${jdbc.driver}"/>
    </bean>
    <!--定义JdbcTemplate Bean-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--将数据源的 Bean 注入到 JdbcTemplate 中-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
   
</beans>

In the above configuration, we have defined two Beans,

  • dataSource is the Bean of the database connection pool object.
  • jdbcTemplate is the Bean of JdbcTemplate, which consists of a property named datasSource.

Spring uses DriverManagerDataSource to manage the database connection pool by default. We can define the Bean of DriverManagerDataSource in Spring's XML configuration file and inject it into the Bean of JdbcTempate.

In dataSource, 4 properties for connecting to the database are defined, as shown in the following table.

attribute name illustrate
driverClassName The driver name used corresponds to the Driver class in the driver JAR package.
url Data source address
username Username to access the database
password Password to access the database

Guess you like

Origin blog.csdn.net/qq_43079001/article/details/132231634