当前位置:网站首页>@Scenario of transactional annotation invalidation
@Scenario of transactional annotation invalidation
2022-07-03 20:48:00 【cristianoxm】
Transactional Used to start a transaction in a project , Then if it is used improperly , It may also lead to transaction invalidation , Look at the following scenario
Embellishment is not public Method 、 modification private、final、static Method:
this 3 In both cases spring Find the reason in the source code of
protected TransactionAttribute computeTransactionAttribute(Method method,
Class<?> targetClass) {
// Don't allow no-public methods as required.
if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
return null;
}
This method checks if the modifier of the target method is public, No public You won't get @Transactional Property configuration information of . and final、static Method cannot be overridden by proxy , It will also lead to transaction invalidation .
Be careful :private,protected、private Decorate the method to use @Transactional annotation , Although the transaction is invalid , But there will be no misstatement , This is a point that we can make mistakes .
- Throw other exceptions manually , rollbackFor Setting error
By default ,spring It just rolls back RuntimeException and Error, For ordinary Excetion( Non runtime exception ), He won't roll back . because spring The team thinks Non runtime exceptions are business , Developers should take the initiative to deal with it rather than throw it out to the framework . If in a transaction Throw other types of exceptions , But expect Spring Ability to roll back transactions , You need to specify rollbackFor attribute .

@Transactional(rollbackFor = MyException.class)
//@Transactional// In this way, the transaction fails
public void withoutRollBackFor(User user) throws MyException {
user.setAge(423442);
userMapper.update(user,new LambdaUpdateWrapper<User>().eq(true, User::getName,user.getName()));
// ordinary Excetion( Non runtime exception ), Transaction failure , Unless otherwise specified @Transactional(rollbackFor = MyException.class)
throw new MyException();
}
- Method calls in the same class , Lead to @Transactional invalid
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public Integer insert(User user){
return userMapper.insert(user);
}
public void test(User user) throws MyException {
// This is actually this.updateStatus(user); instead of proxy Object to call
// Even if an exception is thrown in the end , Because this object is called , therefore updateStatus The transaction of is invalid , After execution age Changed to 423442
updateStatus(user);
}
@Transactional(rollbackFor = MyException.class)
public void updateStatus(User user) throws MyException {
user.setAge(423442);
userMapper.update(user,new LambdaUpdateWrapper<User>().eq(true, User::getName,user.getName()));
throw new MyException();
}
}
Here you can refer to my article
- The exception is catch“ Ate ” Lead to @Transactional invalid
@Transactional(rollbackFor = MyException.class)
public void rollbackFailed(User user){
try {
user.setAge(423442);
userMapper.update(user,new LambdaUpdateWrapper<User>().eq(true, User::getName,user.getName()));
throw new MyException();
}
catch (MyException e){
// Manually roll back the transaction , Otherwise, the transaction fails
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//System.out.println(" Transaction failure ");
}
}
- The database engine does not support transactions
The probability of this is not high , Whether the database engine supports transactions is the key . frequently-used MySQL By default, the database supports transaction innodb engine . Once the database engine is switched to not support transactions myisam, Then the business is fundamentally invalid .
- Multithreaded calls invalidate transactions
- Background introduction
Recently, there is a business scenario of large amount of data insertion and warehousing , You need to make some other modifications first , Then perform the insertion operation , Because inserting data can be a lot ,
Use multithreading to split data and parallel processing to improve response time , If a thread fails to execute , Then roll back all .stay spring Can be used in @Transactional Annotation to control transactions , So that when an exception occurs, it will be rolled back ,
In multithreading , This annotation will not take effect , If the main thread needs to perform some operations to modify the database first , When an exception occurs when the child thread is processing , The data modified by the main thread will not be rolled back , Causing data errors .
- A simple example demonstrates multithreaded transactions
@Transactional(rollbackFor = MyException.class)
public void failedRollBackUnderMultipleThreads(User user) throws MyException {
user.setAge(423442);
userMapper.update(user,new LambdaUpdateWrapper<User>().eq(true, User::getName,user.getName()));
new Thread(()->{
// The transaction method is in another thread , The database links obtained are different , So different from the above is the transaction , Even if an exception is thrown below, rollback , This method will not rollback
roleService.test();
}).start();
throw new MyException();
}
- From the source point of view :
spring The transaction of is realized through database link , A... Is saved in the current thread map,key Data source ,value It's a database link , Only if you have the same database link can you commit and rollback at the same time , In different database connections , It's a different business , Naturally, it is impossible to commit and rollback at the same time
Reference article
About spring Analysis of transaction source code
Reference video
边栏推荐
- 全网都在疯传的《老板管理手册》(转)
- Kubernetes abnormal communication network fault solution ideas
- Battle drag method 1: moderately optimistic, build self-confidence (1)
- Introduction to golang garbage collection
- 11-grom-v2-05-initialization
- Global and Chinese market of electrolyte analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
- Rhcsa third day notes
- How to modify the network IP addresses of mobile phones and computers?
- Brief analysis of ref nerf
- 同花顺开户注册安全靠谱吗?有没有风险的?
猜你喜欢

How to handle wechat circle of friends marketing activities and share production and release skills

强化學習-學習筆記1 | 基礎概念

Basic knowledge of dictionaries and collections

Line segment tree blue book explanation + classic example acwing 1275 Maximum number

Operate BOM objects (key)

JMeter plug-in installation
![C 10 new feature [caller parameter expression] solves my confusion seven years ago](/img/32/2d81237d4f1165f710a27a7c4eb1e1.jpg)
C 10 new feature [caller parameter expression] solves my confusion seven years ago

From the behind the scenes arena of the ice and snow event, see how digital builders can ensure large-scale events

Go learning notes (4) basic types and statements (3)

Such as the visual appeal of the live broadcast of NBA Finals, can you still see it like this?
随机推荐
MDM mass data synchronization test verification
[Yugong series] February 2022 Net architecture class 004 ABP vNext used in WPF project
11-grom-v2-05-initialization
"Designer universe" argument: Data Optimization in the design field ultimately falls on cost, safety and health | chinabrand.com org
Deep search DFS + wide search BFS + traversal of trees and graphs + topological sequence (template article acwing)
浅议.NET遗留应用改造
Global and Chinese market of electrolyte analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
Etcd raft Based Consistency assurance
阻塞非阻塞和同步异步的区分 参考一些书籍
Qt6 QML Book/Qt Quick 3D/基础知识
Instructions for common methods of regular expressions
Global and Chinese market of high temperature Silver sintering paste 2022-2028: Research Report on technology, participants, trends, market size and share
【c】 Digital bomb
Measurement fitting based on Halcon learning -- Practice [1]
Global and Chinese market of micro positioning technology 2022-2028: Research Report on technology, participants, trends, market size and share
Sightseeing - statistics of the number of shortest paths + state transfer + secondary small paths
Get log4net log file in C - get log4net log file in C
Reinforcement learning - learning notes 1 | basic concepts
2022 high voltage electrician examination and high voltage electrician reexamination examination
Camera calibration (I): robot hand eye calibration