场景
数据库连接事务管理是非常重要的功能,当方法对数据库数据进行增加、修改、删除时,如果方法报错,部分数据可能已经写入数据,但整个操作过程是失败的,如何在操作失败时保证数据库数据完整不受污染,需要用到事务,他会在操作异常时,自动回滚数据库数据。
方式和实现
- Spring 事务管理分为编程式和声明式两种方式,编程式需要修改代码,普遍使用声明式实现,这里主要介绍声明式。
- 声明式分两种,配置文件和注解
-
配置文件(xml)中做相关的事务规则声明
- 使用方法
- 第一步:创建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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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"> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="query*" propagation="SUPPORTS" read-only="true"></tx:method> <tx:method name="get*" propagation="SUPPORTS" read-only="true"></tx:method> <tx:method name="select*" propagation="SUPPORTS" read-only="true"></tx:method> <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"></tx:method> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="allManagerMethod" expression="execution (* com.*.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" order="0"/> </aop:config> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
- 第二步:启动类引入
@ImportResource("classpath:transaction.xml")
- 说明
- @Transactional管理的方法,必须发生Exception时有作用,try-catch捕获异常无效。
- 导包:
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency>
- 使用方法
-
@Transactional 注解
- 类别
- spring-boot-starter-jdbc包使用DataSourceTransactionManager
- spring-boot-starter-data-jpa包使用JpaTransactionManager
- 使用方法
- 第一步:导包,先导入两种包jdbc和jpa其中一种
- 第二步:启动类添加注解:@EnableTransactionManagement
- 第三步:server层需要事务管理方法添加@Transactional注解,或整个类添加。
- 说明
- @Transactional管理的方法,必须发生Exception时有作用,try-catch捕获异常无效。
- 类别
-
- 声明式分两种,配置文件和注解
总结
- 无论哪种方案,方法起作用必须抛出异常,负责事务无法起作用。个人比较喜欢xml方式,避免对每个方法进行注解操作。