当前位置:网站首页>@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
边栏推荐
- 1.5 learn to find mistakes first
- University of Electronic Science and technology | playback of clustering experience effectively used in reinforcement learning
- How to handle wechat circle of friends marketing activities and share production and release skills
- CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
- Operate BOM objects (key)
- Node MySQL serialize cannot rollback transactions
- 全网都在疯传的《老板管理手册》(转)
- 2022 melting welding and thermal cutting examination materials and free melting welding and thermal cutting examination questions
- QT tutorial: signal and slot mechanism
- Global and Chinese market of speed limiter 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢
如临现场的视觉感染力,NBA决赛直播还能这样看?
Operate BOM objects (key)
Line segment tree blue book explanation + classic example acwing 1275 Maximum number
APEC industry +: father of the king of the ox mill, industrial Internet "king of the ox mill anti-wear faction" Valentine's Day greetings | Asia Pacific Economic media | ChinaBrand
"Designer universe" APEC safety and health +: environmental protection Panda "xiaobaobao" Happy Valentine's Day 2022 | ChinaBrand | Asia Pacific Economic media
Exercises of function recursion
Reinforcement learning - learning notes 1 | basic concepts
2.1 use of variables
Shortest path problem of graph theory (acwing template)
Measurement fitting based on Halcon learning -- Practice [1]
随机推荐
Thread, thread stack, method stack, the difference of creating thread
University of Electronic Science and technology | playback of clustering experience effectively used in reinforcement learning
CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
In 2021, the global general crop protection revenue was about $52750 million, and it is expected to reach $64730 million in 2028
Basic knowledge of dictionaries and collections
19、 MySQL -- SQL statements and queries
Test changes in Devops mode -- learning and thinking
Etcd raft Based Consistency assurance
Global and Chinese market of charity software 2022-2028: Research Report on technology, participants, trends, market size and share
设计电商秒杀系统
Do you really know how old you are?
@Transactional注解失效的场景
你真的知道自己多大了吗?
MDM mass data synchronization test verification
Wireless network (preprocessing + concurrent search)
In 2021, the global revenue of thick film resistors was about $1537.3 million, and it is expected to reach $2118.7 million in 2028
Assign the CMD command execution result to a variable
Viewing Chinese science and technology from the Winter Olympics (II): when snowmaking breakthrough is in progress
Gauss elimination solves linear equations (floating-point Gauss elimination template)
2.6 formula calculation