@Transactional失效的几种场景

Spring 的 @Transactional 注解控制事务有哪些不生效的场景?

1.数据库引擎不支持事务(仅InnoDB支持)

从 MySQL 5.5.5 开始的默认存储引擎是:InnoDB,之前默认的都是:MyISAM,所以这点要值得注意,底层引擎不支持事务再怎么搞都是白搭。

2.@Transactional 注解只能应用到 public 可见度的方法上

如果要用在非 public 方法上,可以开启 AspectJ 代理模式。

以下来自 Spring 官方文档:

When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.

3..try-catch异常,事务不会生效

也是最常见的一种,把异常吃了,然后又不抛出来,事务也不会回滚!

spring的事务是在调用业务方法之前开始的,业务方法执行完毕之后才执行commit or rollback,

事务是否执行取决于是否抛出runtime异常。如果抛出runtime exception 并在你的业务方法中没有catch到的话,事务会回滚。

这种情况可以用@Transactional(rollbackFor = Exception.class)处理或者再catch里手动执行回滚

@Transactional失效的几种场景_第1张图片

 

4.默认情况下,Spring会对Error或者RuntimeException异常进行事务回滚,

其他继承自java.lang.Exception的异常:如IOException、TimeoutException等,不会回滚。

解决方案:Transactional注解加rollbackFor 属性,指定java.lang.Exception.class;

5.同一个类中方法调用,导致@Transactional失效

场景:开发中避免不了会对同一个类里面的方法调用,比如有一个类Test,它的一个方法A,A再调用本类的方法B

(不论方法B是用public还是private修饰),但方法A没有声明注解事务,而B方法有。则外部调用方法A之后,

方法B的事务是不会起作用的。

原因:由于使用Spring AOP代理造成的,因为只有当事务方法被当前类以外的代码调用时,才会由Spring生成的代理对象来管理。

你可能感兴趣的:(后端Java,springboot,spring,java,后端)