当前位置:网站首页>@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生成的代理对象来管理。
边栏推荐
- KVM常用命令详解
- 力扣每日一题-第29天-219.存在重复元素Ⅱ
- Does the applet input box flash?
- Scalable storage system (I)
- 多项目设计开发·类库项目引入入门
- Chapter IX app project test (3) test tools
- 几个重要的物理概念
- leetcode:494. All methods of adding and subtracting operators to the array to get the specified value
- Unity C# 网络学习(十一)——自定义协议生成工具
- django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3
猜你喜欢

Extensible database (Part 2)

Scalable storage system (I)

以自动化赋能转型,飞鹤乳业加速迈向数字化!

开关电源—Buck电路原理及其仿真

Chapter 14 AC-DC power supply front stage circuit note I

Summary of SQL basic syntax for C #

第九章 APP项目测试(3) 测试工具

Several ways of sharing printers in LAN

Leetcode: monotonic stack structure (Advanced)

云应用、服务的“5层”架构
随机推荐
Web APIs DOM-事件基础丨黑马程序员
门级建模—学习笔记
Li Kou daily question - day 29 -219 Duplicate Element II exists
Detailed explanation of KVM common commands
【小程序实战系列】电商平台源码及功能实现
Understanding and learning of parental delegation mechanism
ambari SSLError: Failed to connect. Please check openssl library versions.
谈云原生,不得不谈的容器
可扩展数据库(下)
TypeError: &# 039; module&# 03…
Lost connection repair: make "hide and seek" nowhere to hide
力扣每日一题-第29天-523.在区间范围统计奇数数目
Lamaba表达式学习及常用函数式接口
Anaconda命令用法
A Preliminary Study of Blackbody radiation
事件委托的原理
English grammar_ Adjective / adverb Level 3 - Comparative_ Useful Expressions
开启创客教育造物学的领域
English grammar_ Adjective / adverb Level 3 - Comparative
Execution plan in MySQL of database Series