springboot框架原理javaweb收藏

springboot @Transaction注解失效之谜

2018-10-26  本文已影响9人  打不开的回忆

使用注解@Transaction声明式事务时,遇到了失效的问题,简要记录,以备后患。

确保已开启TransactionManagment,让你的注解生效

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

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

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

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.

确保调用的是Aop代理类方法而不是目标方法

@Transaction注解基于Aop代理生效,所以只有再使用代理类的带有注解的方法才会生效。比如,方法内 调用同类含有@Transaction注解的其他方法,则执行的是目标类方法(本类方法),而不是代理类的方法,所以不会生效

确保@Transaction的回滚异常

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

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

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;

以上就是常遇到的几个问题,后续开发在遇到类似问题,持续更新!
文章如有不正之处请联系作者进行修改,万分感谢!
微信:


weixin
上一篇下一篇

猜你喜欢

热点阅读