近期在项目开发中,碰到了一个诡异的问题,springboot整合mybatis,开启了事务管理,但业务代码发生自定义异常时,事务未能回滚。最终通过debug,
发现mybatis只能对 RuntimeException 或者 Error类型进行回滚 。调用栈如下:
org.springframework.transaction.interceptor.TransactionAspectSupport
-> protected void completeTransactionAfterThrowing(@Nullable TransactionAspectSupport.TransactionInfo txInfo, Throwable ex)
org.springframework.transaction.interceptor.DefaultTransactionAttribute
-> public boolean rollbackOn(Throwable ex)
代码截图如下:
再查看自定义业务异常,原来是继承至Exception, 因此,事务无法回滚。
最后,将自定义异常继承RunTimeException, 问题完美解决,事务生效。
附录-1:springboot整合 mybatis 开启事务
1.启动类添加注解 @EnableTransactionManagement
2.需要开启事务的方法添加注解 @Transactional