当前位置:网站首页>@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
边栏推荐
- Introduction to golang garbage collection
- Golang type assertion and conversion (and strconv package)
- Analyse de REF nerf
- For in, foreach, for of
- [Yugong series] February 2022 Net architecture class 004 ABP vNext used in WPF project
- 全网都在疯传的《老板管理手册》(转)
- 1.5 learn to find mistakes first
- jvm jni 及 pvm pybind11 大批量数据传输及优化
- Haven't expressed the artifact yet? Valentine's Day is coming. Please send her a special gift~
- JVM JNI and PVM pybind11 mass data transmission and optimization
猜你喜欢

Operate BOM objects (key)
![AI enhanced safety monitoring project [with detailed code]](/img/a9/cb93f349229e86cbb05ad196ae9553.jpg)
AI enhanced safety monitoring project [with detailed code]

Design e-commerce seckill system

Transformer structure analysis and the principle of blocks in it

Based on laravel 5.5\5.6\5 X solution to the failure of installing laravel ide helper

Etcd raft Based Consistency assurance

Derivation of decision tree theory

不同业务场景该如何选择缓存的读写策略?

Q&A:Transformer, Bert, ELMO, GPT, VIT

Basic knowledge of dictionaries and collections
随机推荐
强化学习-学习笔记1 | 基础概念
XAI+网络安全?布兰登大学等最新《可解释人工智能在网络安全应用》综述,33页pdf阐述其现状、挑战、开放问题和未来方向
Kubernetes 通信异常网络故障 解决思路
Basic knowledge of dictionaries and collections
Machine learning support vector machine SVM
From the behind the scenes arena of the ice and snow event, see how digital builders can ensure large-scale events
Pytorch sets the weight and bias of the model to zero
Global and Chinese market of speed limiter 2022-2028: Research Report on technology, participants, trends, market size and share
SQL injection - Fundamentals of SQL database operation
How to set the system volume programmatically- How to programmatically set the system volume?
MySQL master-slave synchronization principle
2022 high voltage electrician examination and high voltage electrician reexamination examination
Global and Chinese market of charity software 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
Example of peanut shell inner net penetration
JMeter plug-in installation
2.7 format output of values
2.3 other data types
How to choose cache read / write strategies in different business scenarios?
19、 MySQL -- SQL statements and queries