一、背景:
目前很多项目的事务处理都是利用Spring的注解式事务实现的(@Transactional)。
- 在测试事务回滚的过程中发现如下现象:
throw new RuntimeException("xxxxxxxxxxxx"); 事务回滚
throw new Exception("xxxxxxxxxxxx"); 事务没有回滚
二、关于spring事务使用说明:
基于Spring AOP的事务管理,即声明式事务管理,默认是针对RuntimeException回滚,既默认只对RuntimeException()及其子类进行事务回滚;非运行时类型的异常默认是不会回滚的。
三、依赖事务管理的业务代码中出现异常该如何处理?
三种回滚处理方式:
1、针对该业务代码进行封装,二次抛出RuntimeException类型的异常;
2、利用硬编码的方式,借助spring api对事务进行显式的回滚;
3、在spring配置文件中对rollback-for属性赋值。Tip:该配置也可以直接加在注解上。
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" rollback-for="com.wangcw.exception.XyzException"/>
</tx:attributes>
</tx:advice>
同时,Spring配置文件中也可以声明出不进行回滚的异常。
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="update*" no-rollback-for="IOException"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>