zoukankan      html  css  js  c++  java
  • SpringBoot

    事务管理的目的

    要么全部成功,要么全部失败,不允许部分成功部分失败。

    回滚失败描述

    ServiceImpl类内部方法的调用。addStudent()方法能够执行,updateStudent()方法因为有错误会抛出异常,但是事务回滚失败。

    原因分析

    直接调用方法,实际上是通过this调用,也就是直接调用了方法,而不是通过Spring上下文获得代理类,因此不会开启事务管理。

    回滚失败的代码

    import org.springframework.transaction.interceptor.TransactionAspectSupport;
    
    @Service
    public class StudentServiceImpl implements IStudentService{
        
        @Transactional(rollbackFor=Exception.class)
        @Override
        public void test(){
          //省略其他业务代码
          addStudent();
          updateStudent();
        }
    
        public void addStudent(){}
    
        public void updateStudent(){}
    
    }
    
    

    正确回滚的代码

    做法:将自身注入Bean。

    import org.springframework.transaction.interceptor.TransactionAspectSupport;
    
    @Service
    public class StudentServiceImpl implements IStudentService{
    
        @Autowired
        StudentImpl studentService; //将自身注入Bean
        
        @Transactional(rollbackFor=Exception.class)
        @Override
        public void test(){
          //省略其他业务代码
          studentService.addStudent();
          studentService.updateStudent();
        }
    
        public void addStudent(){}
    
        public void updateStudent(){}
    
    }
    
    
  • 相关阅读:
    Codeforces 723d [暴力dfs]
    Codeforces 723e [图论][欧拉回路]
    Hihocoder 1035 [树形dp]
    Codeforces 721C [dp][拓扑排序]
    Codeforces 721D [贪心]
    info
    关于string操作
    Floyd求最小环 HDU1599
    Codeforces Round #572 (Div. 2) B Number Circle
    A. XXXXX
  • 原文地址:https://www.cnblogs.com/YuRong3333/p/14536341.html
Copyright © 2011-2022 走看看