当前位置:网站首页>Unexpected rollback exception analysis and transaction propagation strategy for nested transactions
Unexpected rollback exception analysis and transaction propagation strategy for nested transactions
2022-07-25 12:12:00 【JackLi0812】
UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
1. Problem description and recurrence
jfoaProvidesAuditThe function of , The target method ( For example, add users ) Transaction management exists ,
stay Audit You need to query users ( Business management ), Finally, after the target method is executed Audit Insertion of records ( Business management ).
That is, add users ( Business ) Query users in ( Business ) Will throw an exception :
org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
Literally means :
An unpredictable rollback exception occurred , Because the transaction has been flagged, it can only be rolled back , So the transaction rolled back .Now let's reproduce and describe this problem .
@Around("audit()")
public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
Log log = null;
Customer principal = null;
try {
// note1: Get the currently logged in user here , Note that this method can throw exceptions
// 1) getCurrentCustomer In transaction management
// 2) catch The method call did not continue to throw exceptions
principal = customerService.getCurrentCustomer();
} catch (Exception ignore) {
LOGGER.debug("Get principal error!", ignore);
}
// ... Omit some intermediate code
Object result;
try {
// note3: Specific objectives and methods
result = pjp.proceed();
}
catch(Throwable throwable) {
if(log != null) {
log.setMessage("Execute Failed: " + throwable.getMessage());
}
throw throwable;
}
finally {
// ...
}
return result;
}
// note2: The target method is transaction management
@Audit(ResourceEnum.Customer)
@Transactional
@Override
public Integer insertCustomer(@AuditObject("getName()") Customer user) {
if(isValid(user)) {
user.setPassword(
SecurityUtil.generatorPassword(user.getAccount(), user.getPassword()));
return customerDao.insert(user);
}
return null;
}
Pay attention to the above
note1andnote2, In this case, the exception of this article will appear .
2. Principle analysis
because spring Of
@TransactionalThe default transaction propagation strategy of annotation isPropagation.REQUIRED,
PROPAGATION_REQUIRED It means , There's business at the moment , Use the current transaction , If there is no transaction at present, create a transaction . therefore , When
When the target method is called , Because the target method has transactions , When the target method is called, the transaction will be opened ,
When executednote1when ,getCurrentCustomerMethods
There is a business , According to the transaction propagation strategy , spring Will use the transaction of the target method ,
howevergetCurrentCustomerYes try-catch Handle , alsocatchNo more transactions are thrown ,
So whengetCurrentCustomerWhen an exception is thrown , spring To execute rollback operation , however catch
Did not continue to throw exceptions , It will continue to be called untilnote3Continue to execute , When the target method is called
Because it is normal, the call is completed , Therefore, it is necessary to implement commit, So this exception will be thrown .
2.0 Introduction to transaction propagation strategy
spring The following communication strategies are defined :
public enum Propagation {
/** * There's business at the moment , Use the current transaction , If there is no transaction at present, create a transaction */
REQUIRED(TransactionDefinition.PROPAGATION_REQUIRED),
/** * Support current transaction , If it doesn't exist , To execute in a non transactional manner . * notes : For the transaction manager of transaction synchronization , It's a little different from having no business at all , * Because it defines the transaction scope to which synchronization will be applied . * result , Same resources (JDBC Connect 、Hibernate Conversation, etc ) * Will be shared for the entire specified range . Be careful , It depends. * The actual synchronization configuration of the transaction manager . */
SUPPORTS(TransactionDefinition.PROPAGATION_SUPPORTS),
/** * If the current is related to a transaction, the current transaction is used , If there is no transaction at present, an exception will be thrown . */
MANDATORY(TransactionDefinition.PROPAGATION_MANDATORY),
/** * Create a new transaction regardless of whether there is a current transaction . * If there is a current transaction, suspend the current transaction . */
REQUIRES_NEW(TransactionDefinition.PROPAGATION_REQUIRES_NEW),
/** * Run in a non transactional manner , If there is currently a transaction , Then suspend the current transaction */
NOT_SUPPORTED(TransactionDefinition.PROPAGATION_NOT_SUPPORTED),
/** * Run in a non transactional manner , If there is currently a transaction , Throw an exception */
NEVER(TransactionDefinition.PROPAGATION_NEVER),
/** * If the current transaction exists , Then execute... In a nested transaction , Otherwise, the behavior is similar {@code REQUIRED}. * Be careful : The actual creation of nested transactions only applies to specific transaction managers . * This only applies to JDBC DataSourceTransactionManager. * some JTA The provider may also support nested transactions . */
NESTED(TransactionDefinition.PROPAGATION_NESTED);
2.1 Default propagation policy
spring Of
@TransactionalThe default transaction propagation strategy of annotation isPropagation.REQUIRED
public @interface Transactional {
// ...
/** * The transaction propagation type. * <p>Defaults to {@link Propagation#REQUIRED}. * @see org.springframework.transaction.interceptor.TransactionAttribute#getPropagationBehavior() */
Propagation propagation() default Propagation.REQUIRED;
2.2 The problem summary
When methodA call methodB, And both parties have affairs ( Transaction nesting ),
And the communication strategies arePropagation.REQUIREDwhen , It will lead to two methods
Share a transaction ,methodB Mark the transaction as rollback ,methodA in commit This business ,
Then it will appear that the transaction has been marked for rollback (methodB logo ) Exception information for .
3. resolvent
Know the cause of the problem , Naturally, I know the solution , But different business scenarios may have different solutions ,
You need to choose the right solution according to your business scenarios
3.1 modify try-catch
For internal methods methodB Don't go ahead try-catch perhaps catch Continue to throw exception .
3.2 Modify the transaction propagation strategy
- If you modify an external transaction methodA Transaction propagation strategy of , be methodA Only the transaction can be cancelled ( Generally not available ).
- Modify the interior methodB Transaction propagation strategy of , Generally, it can be changed to
REQUIRES_NEW,NOT_SUPPORTED,NESTED.NOT_SUPPORTEDConvert internal transactions into non transactional operations .REQUIRES_NEWWill create a new transaction run .NESTEDRun in nested transactions .
For example, the business scenario here , First is the need for transaction management , So I can use
REQUIRES_NEW,NESTED,
secondly , audit Records and ,getCurrentCustomerAt no time should it affect the operation of core business logic , therefore ,
Finally, I choose to modify the transaction propagation strategy asREQUIRES_NEWTo solve this problem . If your nested transaction is related to the main transaction ,
Then you should chooseNESTED.
Last , One more thing to note : In the same class , Transaction nesting is subject to the outermost method , Nested transactions fail ; Transactions nested in different classes will take effect ;

边栏推荐
- Video Caption(跨模态视频摘要/字幕生成)
- dirReader.readEntries 兼容性问题 。异常错误DOMException
- Brpc source code analysis (VI) -- detailed explanation of basic socket
- 【AI4Code】《CoSQA: 20,000+ Web Queries for Code Search and Question Answering》 ACL 2021
- 【GCN-RS】Region or Global? A Principle for Negative Sampling in Graph-based Recommendation (TKDE‘22)
- 【6篇文章串讲ScalableGNN】围绕WWW 2022 best paper《PaSca》
- 【CTR】《Towards Universal Sequence Representation Learning for Recommender Systems》 (KDD‘22)
- Figure neural network for recommending system problems (imp-gcn, lr-gcn)
- Go 垃圾回收器指南
- Transformer variants (spark transformer, longformer, switch transformer)
猜你喜欢
![[dark horse morning post] eBay announced its shutdown after 23 years of operation; Wei Lai throws an olive branch to Volkswagen CEO; Huawei's talented youth once gave up their annual salary of 3.6 mil](/img/d7/4671b5a74317a8f87ffd36be2b34e1.jpg)
[dark horse morning post] eBay announced its shutdown after 23 years of operation; Wei Lai throws an olive branch to Volkswagen CEO; Huawei's talented youth once gave up their annual salary of 3.6 mil

投屏收费背后:爱奇艺季度盈利,优酷急了?

从云原生到智能化,深度解读行业首个「视频直播技术最佳实践图谱」

【多模态】《TransRec: Learning Transferable Recommendation from Mixture-of-Modality Feedback》 Arxiv‘22

Zero-Shot Image Retrieval(零样本跨模态检索)

Brpc source code analysis (VIII) -- detailed explanation of the basic class eventdispatcher
![[comparative learning] understanding the behavior of contractual loss (CVPR '21)](/img/96/9b58936365af0ca61aa7a8e97089fe.png)
[comparative learning] understanding the behavior of contractual loss (CVPR '21)

给生活加点惊喜,做创意生活的原型设计师丨编程挑战赛 x 选手分享

Power Bi -- these skills make the report more "compelling"“

【AI4Code最终章】AlphaCode:《Competition-Level Code Generation with AlphaCode》(DeepMind)
随机推荐
php 一台服务器传图片到另一台上 curl post file_get_contents保存图片
【GCN-RS】Learning Explicit User Interest Boundary for Recommendation (WWW‘22)
Multi-Label Image Classification(多标签图像分类)
那些离开网易的年轻人
【无标题】
NLP knowledge - pytorch, back propagation, some small pieces of notes for predictive tasks
R语言可视化散点图、使用ggrepel包的geom_text_repel函数避免数据点之间的标签互相重叠(设置min.segment.length参数为Inf不添加标签线段)
flink sql client 连接mysql报错异常,如何解决?
【GCN-RS】Region or Global? A Principle for Negative Sampling in Graph-based Recommendation (TKDE‘22)
[cloud co creation] what is the role of AI in mathematics? What will be the disruptive impact on the mathematical world in the future?
[GCN multimodal RS] pre training representations of multi modal multi query e-commerce search KDD 2022
Power Bi -- these skills make the report more "compelling"“
OSPF comprehensive experiment
【AI4Code】CodeX:《Evaluating Large Language Models Trained on Code》(OpenAI)
Learning to Pre-train Graph Neural Networks(图预训练与微调差异)
【微服务~Sentinel】Sentinel降级、限流、熔断
【GCN-RS】Are Graph Augmentations Necessary? Simple Graph Contrastive Learning for RS (SIGIR‘22)
selenium使用———xpath和模拟输入和模拟点击协作
Brpc source code analysis (VI) -- detailed explanation of basic socket
Qin long, a technical expert of Alibaba cloud: a prerequisite for reliability assurance - how to carry out chaos engineering on the cloud