当前位置:网站首页>@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
边栏推荐
- Battle drag method 1: moderately optimistic, build self-confidence (1)
- Use of CMD command
- Sightseeing - statistics of the number of shortest paths + state transfer + secondary small paths
- JVM JNI and PVM pybind11 mass data transmission and optimization
- Node MySQL serialize cannot rollback transactions
- Global and Chinese markets of active matrix LCD 2022-2028: Research Report on technology, participants, trends, market size and share
- How to do Taobao full screen rotation code? Taobao rotation tmall full screen rotation code
- JVM JNI and PVM pybind11 mass data transmission and optimization
- Camera calibration (I): robot hand eye calibration
- TLS environment construction and plaintext analysis
猜你喜欢
Test changes in Devops mode -- learning and thinking
2.5 conversion of different data types (2)
浅议.NET遗留应用改造
18、 MySQL -- index
你真的知道自己多大了吗?
强化学习-学习笔记1 | 基础概念
Scientific research document management Zotero
[Yugong series] go teaching course 002 go language environment installation in July 2022
Design e-commerce seckill system
Etcd 基于Raft的一致性保证
随机推荐
Rhcsa third day operation
强化学习-学习笔记1 | 基础概念
Global and Chinese markets for medical temperature sensors 2022-2028: Research Report on technology, participants, trends, market size and share
Day6 merge two ordered arrays
Global and Chinese markets of lithium chloride 2022-2028: Research Report on technology, participants, trends, market size and share
11-grom-v2-05-initialization
JS three families
Xai+ network security? Brandon University and others' latest "interpretable artificial intelligence in network security applications" overview, 33 page PDF describes its current situation, challenges,
2.7 format output of values
Fingerprint password lock based on Hal Library
Pytorch sets the weight and bias of the model to zero
2.2 integer
9 pyqt5 qscrollarea scroll area and qscrollbar scroll bar
XAI+网络安全?布兰登大学等最新《可解释人工智能在网络安全应用》综述,33页pdf阐述其现状、挑战、开放问题和未来方向
AI enhanced safety monitoring project [with detailed code]
强化學習-學習筆記1 | 基礎概念
jvm jni 及 pvm pybind11 大批量数据传输及优化
Analysis of gas fee setting under eip1559
[Tang Laoshi] C -- encapsulation: member variables and access modifiers
Global and Chinese market of cyanuric acid 2022-2028: Research Report on technology, participants, trends, market size and share