事务
事务:
- 要么都成功,要么都失败
- 事务很重要,设计到数据一致性问题
- 确保一致性和完整性
事务ACID原则
- 原子性:所有操作要么操作成功,要么全部失败回滚;失败回滚事务操作,对元数据不会有任何影响;
- 一致性:不管任何时间有多少个并发的事务,系统也必须保持统一;
- 隔离性:多个并发的事务执行,在同一时间,只能有一个事务执行;
- 持久性:事务正确执行后,事务中对数据的操作不会回滚;事务一旦提交,无论系统发生什么,结果都不在影响!
编程式事务
在项目中很少使用,这种方式需要注入一个事务管理对象 TransactionTemplate ,然后在我们代码中需要提交事务或回滚事务时自己写代码实现.
声明式事务
管理建立在 AOP 基础上,本质是对方法前后进行拦截,所以声明式事务是方法级别的
xml配置文件实现
<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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置声明事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="datacource" />
</bean>
<!-- 结合AOP,实现事务的织入! -->
<!-- 配置事务的类:spring已经帮我们做了 -->
<!-- 配置事务通知 -->
<tx:advice id="interceptor" transaction-manager="transactionManager">
<!-- 给那些方法配置事务 -->
<!-- 配置事务的传播特性 propagation="REQUIRED" 默认也是required,可以不配 -->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入 -->
<aop:config>
<aop:pointcut id="tx" expression="execution(* com.tian.mapper.*.*(..))"/>
<aop:advisor advice-ref="interceptor" pointcut-ref="tx"/>
</aop:config>
</beans>
注解实现
同样还是需要引入约束文件和开启注解支持
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<tx:annotation-driven/>
</beans>
service层
@Service
@Transactional(propagation=Propagation.REQUIRED)
public class CarsService {
}
事务传播行为
什么叫事务传播行为?
即然是传播,那么至少有两个东西,才可以发生传播。单体不存在传播这个行为。
- 事务传播行为(propagation behavior)指的就是当一个事务方法被另一个事务方法调用时,这个事务方法应该如何进行。
- 事务传播行为是 Spring 框架独有的事务增强特性,他不属于的事务实际提供方数据库行为.
- 例如:methodA 事务方法调用 methodB 事务方法时,methodB 是继续在调 用者 methodA 的事务中运行呢,还是为自己开启一个新事务运行,这就是由 methodB 的事务传播行为决定的。
事务传播7中行为
事务传播行为类型 | 说明 |
---|---|
PROPAGATION_REQUIRED | 如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。这是最常见的选择。 |
PROPAGATION_SUPPORTS | 支持当前事务,如果当前没有事务,就以非事务方式执行。 |
PROPAGATION_MANDATORY | 使用当前的事务,如果当前没有事务,就抛出异常。 |
PROPAGATION_REQUIRES_NEW | 新建事务,如果当前存在事务,把当前事务挂起。 |
PROPAGATION_NOT_SUPPORTED | 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。 |
PROPAGATION_NEVER | 以非事务方式执行,如果当前存在事务,则抛出异常。 |
PROPAGATION_NESTED | 如果当前存在事务,则在嵌套事务内执行。如果当前没有事 ,则执行与PROPAGUATION_REQURIED类似的操作。 |
事务传播失效
- 不能在同一个类的方法相互调用
- 出现异常被catch捕获
- 修饰非public方法
- 错误配置事务传播行为