当前位置:网站首页>@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
边栏推荐
- Global and Chinese market of electrolyte analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
- Thread, thread stack, method stack, the difference of creating thread
- Fingerprint password lock based on Hal Library
- Cannot load driver class: com. mysql. cj. jdbc. Driver
- Global and Chinese market of high purity copper foil 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese market of two in one notebook computers 2022-2028: Research Report on technology, participants, trends, market size and share
- Cap and base theory
- Wireless network (preprocessing + concurrent search)
- JVM JNI and PVM pybind11 mass data transmission and optimization
- JVM JNI and PVM pybind11 mass data transmission and optimization
猜你喜欢
18、 MySQL -- index
Test changes in Devops mode -- learning and thinking
你真的知道自己多大了吗?
Xai+ network security? Brandon University and others' latest "interpretable artificial intelligence in network security applications" overview, 33 page PDF describes its current situation, challenges,
MDM mass data synchronization test verification
设计电商秒杀系统
全网都在疯传的《老板管理手册》(转)
2.5 conversion of different data types (2)
How can the outside world get values when using nodejs to link MySQL
如临现场的视觉感染力,NBA决赛直播还能这样看?
随机推荐
如临现场的视觉感染力,NBA决赛直播还能这样看?
Plan for the first half of 2022 -- pass the PMP Exam
MySQL dump - exclude some table data - MySQL dump - exclude some table data
Global and Chinese markets for medical temperature sensors 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese market of high temperature Silver sintering paste 2022-2028: Research Report on technology, participants, trends, market size and share
Interval product of zhinai sauce (prefix product + inverse element)
[Yugong series] go teaching course 002 go language environment installation in July 2022
What is the maximum number of concurrent TCP connections for a server? 65535?
"Designer universe" APEC safety and health +: environmental protection Panda "xiaobaobao" Happy Valentine's Day 2022 | ChinaBrand | Asia Pacific Economic media
Qt6 QML Book/Qt Quick 3D/基础知识
阻塞非阻塞和同步异步的区分 参考一些书籍
同花顺开户注册安全靠谱吗?有没有风险的?
Assign the CMD command execution result to a variable
Instructions for common methods of regular expressions
Global and Chinese market of two in one notebook computers 2022-2028: Research Report on technology, participants, trends, market size and share
In 2021, the global revenue of syphilis rapid detection kits was about US $608.1 million, and it is expected to reach US $712.9 million in 2028
JVM JNI and PVM pybind11 mass data transmission and optimization
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of rotary tablet presses in the global market in 2022
Test changes in Devops mode -- learning and thinking
[Tang Laoshi] C -- encapsulation: member variables and access modifiers