当前位置:网站首页>@Transactional失效的几种场景
@Transactional失效的几种场景
2022-06-28 03:24:00 【云上上云】
Spring 的 @Transactional 注解控制事务有哪些不生效的场景?
1.数据库引擎不支持事务(仅InnoDB支持)
从 MySQL 5.5.5 开始的默认存储引擎是:InnoDB,之前默认的都是:MyISAM,所以这点要值得注意,底层引擎不支持事务再怎么搞都是白搭。
[email protected]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里手动执行回滚

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生成的代理对象来管理。
边栏推荐
- 数据库系列之MySQL配置F5负载均衡
- INFO:  HHH000397:  Using…
- 谈云原生,不得不谈的容器
- GCD maximum common divisor
- 【小程序实战系列】电商平台源码及功能实现
- 数据库系列之MySQL中的分页查询优化
- 第一章 Bash 入门
- A solution to the inefficiency of setting debug mode in developing flask framework with pychar
- Scalable storage system (I)
- django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3
猜你喜欢

第一章 Bash 入门

vscode中出现无法在只读编辑器中编辑

Leetcode: monotonic stack structure (Advanced)

光的粒子说(光电效应/康普顿效应)

leetcode:单调栈结构(进阶)

数字电路学习笔记(二)

Arrangement of basic electrical knowledge (II)

Understanding and learning of parental delegation mechanism

Simple implementation of cool GUI window based on WPF

Lost connection repair: make "hide and seek" nowhere to hide
随机推荐
Li Kou daily question - day 29 -575 Divide candy
数据库系列之MySQL配置F5负载均衡
One article tells you what kubernetes is
Lamaba表达式学习及常用函数式接口
PyCharm设置仿sublime配色方案
继承
力扣每日一题-第29天-523.在区间范围统计奇数数目
Circular sliding auto adsorption UI tool that monkeys can use
小程序的防抖节流怎么写?
光的粒子说(光电效应/康普顿效应)
第一个.net core MVC项目
MySQL master-slave replication, separation and resolution
Lost connection repair: make "hide and seek" nowhere to hide
工业物联网将取代人工发展吗?
Chapter 14 AC-DC power supply front stage circuit note I
【Linux】【Mysql】ERROR 1698 (28000): Access denied for user ‘root‘@‘localhost‘
[graduation season] graduate summary
Summary of SQL basic syntax for C #
Pychart shares third-party modules among different projects
Go 数据类型篇(四)之浮点型与复数类型