How to perform JDBC operation through Spring framework?

How to perform JDBC operation through Spring framework?

How Spring integrates JDBC

  • Add dependency
  • Write the configuration file db.properties
  • bean.xml configuration modification
  • Configure data source
  • Template class configuration
  • Test integration results

Case practice

Add dependency

Database driver jar package

mysql-connector-java-5.1.25-bin.jar

Database connection pool related jar package

c3p0-0.9.5.2.jar、mchange-commons-java-0.2.11.jar

Spring jdbc related jar

spring-jdbc-4.3.2.RELEASE.jar、spring-tx-4.3.2.RELEASE.jar
<!-- spring 框架坐标依赖添加 --> 
<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-context</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<!-- aop --> 
<dependency> 
    <groupId>org.aspectj</groupId> 
    <artifactId>aspectjweaver</artifactId> 
    <version>1.8.9</version>
</dependency>
<!-- mysql 驱动包 --> 
<dependency> 
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId> 
    <version>5.1.39</version>
</dependency>
<!-- c3p0 连接池 --> 
<dependency> 
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>
<!-- spring jdbc --> 
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId> 
    <version>4.3.2.RELEASE</version>
</dependency>
<!-- springs事务 --> 
<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-tx</artifactId> 
    <version>4.3.2.RELEASE</version>
</dependency>

Configuration file db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_jdbc?useUnicode=true&characterEncod
ing=utf8
jdbc.user=root
jdbc.password=root

mysql8版本以上
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/user?useSSL=false&amp;serverTimezone=UTC&amp;allowPublicKeyRetrieval=true
jdbc.user=root
jdbc.password=root

The following is optional configuration

initialPoolSize=20 
maxPoolSize=100 
minPoolSize=10 
maxIdleTime=600 
acquireIncrement=5 
maxStatements=5 
idleConnectionTestPeriod=60

bean.xml configuration modification

Load properties file configuration

<!-- 加载 properties 配置文件 --> 
<context:property-placeholder location="db.properties" />
<?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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task.xsd">
    <!-- 加载properties 配置文件 --> 
    <context:property-placeholder location="db.properties" />
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property> 
        <property name="user" value="${jdbc.user}"></property> 
        <property name="password" value="${jdbc.password}"></property>
    </bean> 
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">                 
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

Configure data source

Since establishing a database connection is a very time-consuming and resource-consuming behavior, some connections are established with the database in advance through the connection pool and placed in memory. When the application needs to establish a database connection, it can directly apply for one in the connection pool, and then use it. put it back.

C3P0 and dbcp a second election to

​ DBCP (DataBase connection pool), database connection pool. It is a java connection pool project on apache and a connection pool component used by tomcat. To use dbcp alone requires two packages: commons-dbcp.jar, commons-pool.jar dbcp, and there is no automatic recovery of idle connections .

​ C3P0 is an open source JDBC connection pool, which implements a data source, supports the JDBC3 specification and JDBC2 standard extensions. Open source projects currently using it include Hibernate, Spring, etc. c3p0 has the function of automatically reclaiming idle connections

C3P0 data source configuration

<!-- 配置 c3p0 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${driver}"></property>
    <property name="jdbcUrl" value="${url}"></property>
    <property name="user" value="${user}"></property>
    <property name="password" value="${password}"></property>
</bean>

C3P0 other additional configuration (the corresponding values ​​are specified in the db.properties file)

<!-- 指定连接池中保留的最大连接数. Default:15--> 
<property name="maxPoolSize" value="${maxPoolSize}"/> 
<!-- 指定连接池中保留的最小连接数--> 
<property name="minPoolSize" value="${minPoolSize}"/> 
<!-- 指定连接池的初始化连接数 取值应在 minPoolSize 与 maxPoolSize 之 间.Default:3--> 
<property name="initialPoolSize" value="${initialPoolSize}"/> 
<!-- 最大空闲时间,60 秒内未使用则连接被丢弃。若为 0 则永不丢弃。 Default:0--> 
<property name="maxIdleTime" value="${maxIdleTime}"/> 
<!-- 当连接池中的连接耗尽的时候 c3p0 一次同时获取的连接数. Default:3--> 
<property name="acquireIncrement" value="${acquireIncrement}"/> 
<!-- JDBC 的标准,用以控制数据源内加载的 PreparedStatements 数量。
但由于预缓存的statements属于单个connection而不是整个连接池所以设置这个参数需要
考虑到多方面的因数.如果 maxStatements 与 maxStatementsPerConnection 均为 0,则缓存
被关闭。Default:0--> 
<property name="maxStatements" value="${maxStatements}"/> 
<!-- 每 60 秒检查所有连接池中的空闲连接.Default:0 --> 
<property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"/>

The dbcp data source configuration is as follows:

<!-- 配置 dbcp 数据源-->
<bean id="myDataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${driver}" />
    <property name="url" value="${url}"/>
    <property name="username" value="${user}"/>
    <property name="password" value="${password}"/>
    <!-- 连接池启动时的初始值 --> 
    <property name="initialSize" value="1"/> 
    <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到 maxIdle 为止 --> 
    <property name="maxIdle" value="2"/> 
    <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请一些连接,以避免洪峰来时再申请而造成的性能开销 --> 
    <property name="minIdle" value="1"/> 
</bean>

Template class configuration

Spring establishes the repeated operations in JDBC into a template class: org.springframework.jdbc.core.JdbcTemplate, which is added to the configuration file

<!-- jdbcTemplate 配置 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
</bean>

Test integration results

Test whether the jdbcTemplate bean is obtained through junit

public class TestSpringJdbc {
    private JdbcTemplate jdbcTemplate;
    @Before
        public void init(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
        jdbcTemplate=(JdbcTemplate) ctx.getBean("jdbcTemplate");
    }
    @Test
    public void test() {
        String sql="select count(1) from account";
        Integer total= jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println("总计路数:"+total);
    }
}

Expand

JDBC transaction

If the application directly uses JDBC for persistence, then use DataSourceTransactionManager to handle the transaction boundary. In order to use DataSourceTransactionManager, you need to assemble it into the context definition of the application using the following XML:

<bean id="transactionManager" 
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

In fact, DataSourceTransactionManager manages transactions by calling java.sql.Connection, and the latter is obtained through DataSource. Commit the transaction by calling the commit() method of the connection. Similarly, if the transaction fails, it will be rolled back by calling the rollback() method.

Guess you like

Origin blog.51cto.com/15064873/2571146