事务的分类
编程式事务:是指在代码中手动的管理事务,缺点:代码侵入性太强
try{
//todo something
transactionManager.commit(status);
}catch(Exception e){
transactionManager.rollback(status);
throw new myException("", e);
}
声明式事务:基于AOP面向切面,将业务与事务解耦,代码侵入性很低。
声明式事务有两种实现方式:
- 基于AspectJ的xml方式配置
<!-- 定义事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理增强 -->
<!-- 配置事务管理增强 需要指定一个事物管理器-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- 定义切面 -->
<aop:config>
<!-- 定义切入点,及切入点的表达式 和id -->
<aop:pointcut id="serviceMethod"
expression="execution(* cn.kgc.service..*.*(..))" />
<!-- 把增强的引用和切入点的引用组合起来-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
</aop:config>
- 基于注解的配置
<!-- 定义事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 开启事务控制的注解支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
@Transactional
public class ServiceImpl implements Service {
@Autowired
private Dao dao;
@Override
public void insert(Test test) {
dao.insert(test);
//抛出unchecked异常,触发事物,回滚
throw new RuntimeException("test");
}
参考:https://blog.csdn.net/qq_41205144/article/details/84577162
https://baijiahao.baidu.com/s?id=1661650900351466294&wfr=spider&for=pc
网友评论