码迷,mamicode.com
首页 > 其他好文 > 详细

Transaction rolled back because it has been marked as rollback-only

时间:2020-12-28 11:13:28      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:machine   控制   tle   调用   content   默认   rgba   row   aspect   

嵌套事务异常Transaction rolled back because it has been marked as rollback-only导致的原因和处理方法

参考:https://fangshixiang.blog.csdn.net/article/details/80445912?utm_medium=distribute.pc_relevant.none-task-blog-searchFromBaidu-2.not_use_machine_learn_pai&depth_1-utm_source=distribute.pc_relevant.none-task-blog-searchFromBaidu-2.not_use_machine_learn_pai

根本原因:手动捕捉了事务中的异常导致事务失效,提交已经标记必须回滚的事务

例如:

@Transactional
public void testA(){
    mapper.insert(...)
    try{
        testB();
    }catch(Exception e){
      e.printStackTrace();
    }
}
@Transactional
public void testB(){
      int a = 1/0;  
}

testA和testB都需要事务,事务传播属性默认为REQUIRED,调用testA时,创建新事务,调用testB时已经有事务了,则加入testA的事务,当发生异常时,拦截器拦截到testB异常,将共同的事务标记为rollback-only

testA方法中由于使用了try catch,导致事务失效,截器无法捕捉到异常,testA正常提交,提交时发现事务已经被标记成rollback-only了,所以会抛出Transaction rolled back because it has been marked as rollback-only

解决办法:

1. 不要在事务控制的方法中手动try catch 捕捉异常

2. 在try catch中捕捉到异常后继续抛出,让拦截器拦截到

2.在catch中手动回滚 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动设置回滚

@Transactional
public void testA(){
    mapper.insert(...)
    try{
        testB();
    }catch(Exception e){
      e.printStackTrace();
// 以下方法二选一
//1. 设置手动回滚 TransactionAspectSupport.currentTransactionStatus() .setRollbackOnly();
//2. 继续往外抛出异常
throw new RuntimeException(e.toString); } } @Transactional
public void testB(){ int a = 1/0; }

 

 

 

Transaction rolled back because it has been marked as rollback-only

标签:machine   控制   tle   调用   content   默认   rgba   row   aspect   

原文地址:https://www.cnblogs.com/zincredible/p/14170703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!