我是靠谱客的博主 烂漫猫咪,这篇文章主要介绍SpringJDBC模板的使用以及实现事务管理一、SpringJDBC模板三、结论,现在分享给大家,希望可以做个参考。

文章目录

  • 一、SpringJDBC模板
    • 1.1 使用SpringJDBC模板
      • 1.1.1前期准备
    • 二、Spring实现事务管理
    • 2.1 进行事务管理的原因
    • 2.2 xml的事务管理配置
    • 2.3 注解配置
  • 三、结论

一、SpringJDBC模板

·  当还未接触到SpringJDBC模板以及Mybatis等框架时,我们一直在使用DButils来对JDBC进行封装操作,SpringJDBC模板和DButils的操作可以说是十分相似。所以我们操作起来几乎没有难度,相比DBUtils需要额外引入连接池才可以使用,Spring自己内置了连接池(DriverManagerDataSource),可以说是十分方便。
·  使用SpringJDBC模板需要的jar包是:spring-jdbc
·  与数据库交互需要使用:mysql-connection-java

1.1 使用SpringJDBC模板

·  使用SpringJDBC模板特别简单,只需要两个步骤:

  1. 配置DriverManagerDataSource连接池,并注入jdbcTemplate对象
  2. 使用JdbcTemplate对象来进行数据库的交互
    • JdbcTemplate的使用几乎和dbutils一样,查询用query,增删改用update,参数也是差不多。其中查询操作,DButils使用的返回值接口是ResultSetHandle< T >,而Spring所用的接口是RowMapper< T >,我们一般用其实现类BeanPropertyRowMaper< T >

1.1.1前期准备

  • 引入jar包,Maven依赖如下
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--用于Spring整合tesng测试--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.0.0</version> </dependency> <!--使用SpringJDBCTemplate--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies>
  • 把DataSource和jdbcTemplate交给SpringIOC去管理(非自己定义的bean用xml创建),同时开启组件扫描,xml完整配置如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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:contxt="http://www.springframework.org/schema/context" 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"> <contxt:component-scan base-package="com.memoforward"/> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///springaop"/> <property name="username" value="root"/> <property name="password" value="123"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
  • 创建数据库springaop,并创建客户表t_account
idanamemoney
1cxy2000.0
2lhw2000.0
  • 编写Account端的操作,只编写通过客户姓名查询以及更新客户的操作(因为事务管理要用)
    //AccountDao
复制代码
1
2
3
4
5
6
7
package com.memoforward.dao; import com.memoforward.domain.Account; public interface AccountDao { public Account findAccountByName(String accountName); public void update(Account account); }

//AccountDaoImpl

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.memoforward.dao.impl; import...; import java.util.List; @Repository("accountDao") public class AccountDaoImpl implements AccountDao { @Autowired JdbcTemplate jdbcTemplate; @Override public Account findAccountByName(String accountName) { List<Account> aList = jdbcTemplate.query("select * from t_account where aname = ?", new BeanPropertyRowMapper<Account>(Account.class), accountName); if(aList.size() != 1) throw new RuntimeException("查询失败..."); return aList.get(0); } @Override public void update(Account account) { jdbcTemplate.update("update t_account set aname=?,money=? where id = ?",account.getAname(),account.getMoney(),account.getId()); } }

`  可见,SpringTemplate还是相当简单的,没有什么特殊的思想,对开发来说并没有方便很多,这里就不进行测试了。
·  这里注意一下:JDBC实现了threadLocal,所以即使它是单例的,也是线程安全的 (说实话我不是很懂…,以后成长起来再来解释一下),它会根据当前的线程去取数据库的连接。

二、Spring实现事务管理

·  有关事务管理的内容,不是本博客的重点,本篇文章只是略微介绍一下Spring事务管理的使用(因为这个是相当的方便)。Spring事务管理是基于AOP的,用来增强业务层的业务逻辑,有兴趣可以参考我关于AOP的教程:SpringAOP实战。

2.1 进行事务管理的原因

·  虽然不着重讲事务管理的细节,但是这里给出一个特别经典的案例:转帐案例,来表明事务管理的重要性。
·  我们在业务层实现一个转账方法,并设置一点小细节:模拟在转账过程中的停电事件,停电的时间点在:甲方已经转账成功,但乙方还未收到钱。停电事件用一个flag控制。
业务层实现如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.memoforward.service.impl; import...; @Service("accountService") public class AccountServiceImpl implements AccountService { @Autowired AccountDao accountDao; @Override public void transfer(String sourceName, String targetName, Double money, boolean flag) { Account source = accountDao.findAccountByName(sourceName); Account target = accountDao.findAccountByName(targetName); source.setMoney(source.getMoney() - money); target.setMoney((target.getMoney() + money)); accountDao.update(source); if(flag) throw new RuntimeException("断电了...."); accountDao.update(target); } }

如果我们设置flag为true,并进行转账:

复制代码
1
2
3
4
5
6
@Test public void testTranser(){ accountService.transfer("cxy","lhw",1000.0,true); }

数据库里的金额就变成了:可见1号的钱少了,结果2号的钱没多。

idanamemoney
1cxy1000.0
2lhw2000.0

造成这种现象的原因很简单,因为:业务层会调用持久层(DAO)的方法,默认情况是:每次dao层的方法执行结束之后,事务都被自动提交了。
·  因此,就需要对这个转账方法进行事务的管理:开启事务,如果异常就回滚,不异常就用提交,最后是释放连接。我在之前的文章里,用动态代理实现了事务管理,有兴趣可以参考一下:Java两种动态代理实战+动态代理死循环的解释。
·  因为Spring中声明事务管理是基于aop的,所以很显然,事务管理的内容必然就是一个advice通知。而相比普通的切面,事务管理很常用,因此spring就自己把其封装了。

2.2 xml的事务管理配置

  • 首先还是要引入相应的jar包:spring-tx和aspectjweaver,一个是事务管理的依赖,一个是用于识别切入点表达式。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.2</version> </dependency>
  • 配置步骤:
  1. 配置事务管理器(DataSourceTransactionManagement)并注入Datasource。(事务管理器的接口是PlatformTransactionManagement)
  2. 配置事务通知< tx:advice >并将事务管理器添加至标签属性
  3. 配置aop,写切入点表达式并用< aop: advisor >引入事务通知
  4. 在事务通知下配置子标签< tx:attributes > ,在< tx:attrributes >标签下用< tx:method >配置业务方法(只有配置了切入点才能知道增强哪个包的方法,因此这步在最后)
  • xml配置如下:注意事务管理是业务层的和持久层没有关系。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?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:contxt="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <contxt:component-scan base-package="com.memoforward"/> <!-- 1.配置事务管理器--> <bean id="txManagement" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 2.配置事务通知并引入事务管理器--> <tx:advice id="txAdvice" transaction-manager="txManagement"> <!-- 4.配置事务增强属性--> <tx:attributes> <!-- 6.对不同的方法进行不同的事务管理--> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 3.开启aop并引入事务通知--> <aop:config> <aop:pointcut id="pt1" expression="execution(* com.memoforward.service.impl.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///springaop"/> <property name="username" value="root"/> <property name="password" value="123"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
  • 关于< tx:method >的属性:这个标签是针对不同的方法进行不用的事务增强而设计出来的,spring为其提供了6种属性:
属性含义
isolation用于指定事务的隔离级别。默认是数据库的默认隔离级别。
propagation用于指定事务的传播行为。默认值是:REQUIRED,表示一定会开启事务。也有SUPPORTS表示支持当前事务(如果当面没有事务,则不开启事务),一般用于查询方法。
read-only用于指定事务是否只读。只有查询方法才能是true。
timeout用于指定事务的超时时间,默认是-1,表示永不超时。设置的单位级别是秒。
rollback-for用于指定一个异常,当产生该异常时,事务回滚,产生其他异常,事物不回滚。不设置则所有异常都回滚 。
no-rollback-for用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常,事物回滚。不设置则所有异常都回滚 。
  • 结果:这就不进行测试了,因为非常简单。当配置了如上的事务后,在“转账”操作未结束的时候,所有的dao方法都不会提交,因此保证了转账的安全性。

2.3 注解配置

·  Spring事务管理同样也可以进行注解配置,注解配置比较简单,但是有不方便的地方。
·  Spring进行注解配置的步骤是:

  1. 配置事务管理器
  2. 开启Spring对注解配置事务的支持(< tx:annotation-driven >),纯注解配置的话在配置类上用@EnableTransactionManagement来开启。
  3. 在需要事务支持的地方使用@Transactional,其属性就是上述标签< tx:method > 的属性。这个注解用在类上表示此种事务对该类的所有方法都生效;用在方法上表示:此种事务仅对该方法生效。注意:我还不太清楚如果使用该注解对不同的事务管理器进行操作。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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:contxt="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <contxt:component-scan base-package="com.memoforward"/> <bean id="txManagement" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="txManagement"/> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///springaop"/> <property name="username" value="root"/> <property name="password" value="123"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>

其业务层改为如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.memoforward.service.impl; import ...; @Service("accountService") @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class AccountServiceImpl implements AccountService { @Autowired AccountDao accountDao; @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void transfer(String sourceName, String targetName, Double money, boolean flag) { Account source = accountDao.findAccountByName(sourceName); Account target = accountDao.findAccountByName(targetName); source.setMoney(source.getMoney() - money); target.setMoney((target.getMoney() + money)); accountDao.update(source); if(flag) throw new RuntimeException("断电了...."); accountDao.update(target); } }
  • 结果:进行了该注解配置后,转账操作也正常回滚了。

三、结论

·  Spring声明式事务管理十分有用,用起来很方便,就是需要记忆的部分有点多,不过孰能生巧,多练多写才是王道。这里Spring有关业务层的内容就全部结束。我最近也变的很忙,关于java后台的学习笔记也要稍微停滞一段时间。闲暇之余可能会更新一些有关深度学习的内容(为了毕业),加油吧。

最后

以上就是烂漫猫咪最近收集整理的关于SpringJDBC模板的使用以及实现事务管理一、SpringJDBC模板三、结论的全部内容,更多相关SpringJDBC模板内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(85)

评论列表共有 0 条评论

立即
投稿
返回
顶部