通过 Spring 框架如何进行JDBC操作呢?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XS2e0fOJ-1601453488065)(https://imgkr.cn-bj.ufileos.com/50416f44-5b7e-43bb-a0c4-ee71be577c04.jpg)]

## Spring 整合 JDBC 的方式

- 添加依赖

- 编写配置文件 db.properties

- bean.xml 配置修改

- 配置数据源

- 模板类配置

- 测试整合结果

## 案例实操

### 添加依赖

#### 数据库驱动 jar 包

~~~ java

mysql-connector-java-5.1.25-bin.jar

~~~

#### 数据库连接池相关 jar 包

~~~ java

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

~~~

#### Spring jdbc 相关 jar

~~~java

spring-jdbc-4.3.2.RELEASE.jar、spring-tx-4.3.2.RELEASE.jar

~~~

~~~ xml

<!-- 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>

~~~

###  配置文件db.properties

~~~ java

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

~~~

**以下为可选配置**

~~~java

initialPoolSize=20

maxPoolSize=100

minPoolSize=10

maxIdleTime=600

acquireIncrement=5

maxStatements=5

idleConnectionTestPeriod=60

~~~

### bean.xml 配置修改

**加载 properties 文件配置**

~~~ xml

<!-- 加载 properties 配置文件 -->

<context:property-placeholder location="db.properties" />

~~~

~~~ xml

<?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>

~~~

### **配置数据源**

由于建立数据库连接是一个非常耗时耗资源的行为,所以通过连接池预先 同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连 接池中申请一个就行,用完后再放回去。

​ **C3P0** **与** **dbcp** **二选一即可**

​ DBCP(DataBase connection pool),数据库连接池。是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用 dbcp 需要 2 个包:commons-dbcp.jar,commons-pool.jar dbcp,**没有自动回收空闲连接的功能**.

​ C3P0 是一个开源的 JDBC 连接池,它实现了数据源,支持 JDBC3 规范和 JDBC2 的标准扩展。目前使用它的开源项目有 Hibernate,Spring 等。**c3p0 有自动回收空闲连接功能**

**C3P0 数据源配置**

~~~ xml

<!-- 配置 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 其他额外配置(对应的值在 db.properties 文件中指定)**

~~~xml

<!-- 指定连接池中保留的最大连接数. 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}"/>

~~~

**对于 dbcp 数据源配置如下:**

~~~ xml

<!-- 配置 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>

~~~

### 模板类配置

Spring 把 JDBC 中重复的操作建立成了一个模板类:org.springframework.jdbc.core.JdbcTemplate ,配置文件中加入

~~~xml

<!-- jdbcTemplate 配置 -->

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="dataSource"></property>

</bean>

~~~

### 测试整合结果

**通过 junit 测试 jdbcTemplate bean 是否获取到**

~~~ java

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);

}

}

~~~

## 扩展

### JDBC 事务

如果应用程序中直接使用 JDBC 来进行持久化,此时使用 DataSourceTransactionManager 来处理事务边界。为了使用 DataSourceTransactionManager,需要使用如下的 XML 将其装配到应用程序的上下文定义中:

~~~ xml

<bean id="transactionManager"

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource" />

</bean>

~~~

界。为了使用 DataSourceTransactionManager,需要使用如下的 XML 将其装配到应用程序的上下文定义中:

~~~ xml

<bean id="transactionManager"

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource" />

</bean>

~~~

实际上,DataSourceTransactionManager 是通过调用 java.sql.Connection 来管理事务, 而后者是通过 DataSource 获取到的。通过调用连接的 commit()方法来提交事务,同样,事务失败则通过调用 rollback()方法进行回滚。

需要项目资料源码+我们程序员小姐姐v:lezijie007(加好友时备注:B站-LT,不备注拒绝添加哟)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容