上文@Transactional事务注解失效篇(一)中我们提到了在同个类下调用方法的事务失效情况,实际上使@Transactional事务注解失效的情况还有很多,这里我就不再重复造车轮,在网上看到篇写得挺不错的博文把我想说的都说了,所以借花献佛罗列下其它可能使事务失效的情况。(转自:springboot @Transaction注解失效之谜

1. 确保已开启TransactionManagment

  1. 如果你的项目引入了boot-starter的jbdc或jpa包,则不需要自己配置DataSourceTransactionManager,springboot自动配置特性会帮你配置。
  2. 如果未正确配置,则需在Application启动类上,使用注解@EnableTransactionManagement让springboot帮你配置。
  3. 不建议重写config类,自己实现改配置

2. 确保正确使用声明式注解@Transactional

springframework下的注解包类名全称:org.springframework.transaction.annotation.Transactional

3. 确保注解作用域的方法修饰符

  1. @Transaction作用于类上,则该类下的所有public方法生效
  2. @Transaction作用于方法上,只有public修饰的方法生效,其余不生效
  3. @Transaction最好作用于类/或类的的方法上,而不是接口/或接口的方法上,因为作用于接口上你必须保证使用的是JDK动态代理而不是CGLB代理。下面是来自springboot官网的解释:

The Spring team recommends that you annotate only concrete classes (and methods of concrete classes) with the @Transactional annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you use interface-based proxies. The fact that Java annotations are not inherited from interfaces means that, if you use class-based proxies (proxy-target-class=”true”) or the weaving-based aspect (mode=”aspectj”), the transaction settings are not recognized by the proxying and weaving infrastructure, and the object is not wrapped in a transactional proxy, which would be decidedly bad.

4. 确保调用的是aop代理类方法而不是目标方法

@Transaction注解基于aop代理生效,所以只有在使用代理类的带有注解的方法才会生效。比如,方法内调用同类含有@Transaction注解的其他方法,则执行的是目标类方法(本类方法),而不是代理类的方法,所以不会生效。这里也就是我们上一篇提到的内容。

5. 确保@Transaction的回滚异常

  1. 手动try/catch吃掉异常,显然不会回滚
  2. 未正确声明回滚/不回滚的异常类型,注解默认回滚RuntimeException和Error,其他查询异常不会回滚,可以使用@Transaction的rollbackFor和noRollbackFor属性设置异常类型

6. 确保数据库表引擎支持事务

使用JPA的spring.jpa.hibernate.ddl-auto配置自动创建的表,默认引擎是engine=MyISAM,是不支持事务的,使用JPA时要注意这点,建议不要打开自动创建表配置。
查看/修改数据库表引擎的命令:

1
2
3
4
5
6
7
8
9
10
11
12
show create TABLE customer;

CREATE TABLE `customer` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`address` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`phone` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=38 DEFAULT CHARSET=utf8

ALTER TABLE customer ENGINE = INNODB;