@Transactional注解加不加 rollbackFor = Exception.class 的区别

(1)@Transactional可以回滚   

 

<update id="test">
        UPDATE tbl_users set delflag='0' where account='admin'
 </update>

 

 

@Override
  @Transactional
    public Ret test(){
        int i = articleMapper.test();
        int a = 2/0;
        if(i > 0){
            ResultUtil.success();
        }
        return ResultUtil.error();
    }

 

ArithmeticException这个异常类是继承了RuntimeException

@Transactional默认回滚的的异常就是RuntimeException

untimeException又是继承Exception

 

只要是RuntimeExceptionRuntimeException下面的子类抛出的异常 @Transactional都可以回滚的

 

(2)、、、、、、、、、、、、、@Transactional不能过滚的异常@Override
@Transactional
public Ret test() throws Exception {
    int i = articleMapper.test();

    try {
        int a = 2 / 0;
    } catch (Exception e) {
        throw new Exception();
    }
    if (i > 0) {
        ResultUtil.success();
    }
    return ResultUtil.error();
}

 

@Transactional并不能回滚Exception异常

////////////

总结一下

@Transactional只能回滚RuntimeExceptionRuntimeException下面的子类抛出的异常 不能回滚Exception异常

如果需要支持回滚Exception异常请用@Transactional(rollbackFor = Exception.class)

这里如果是增删改的时候我建议大家都使用@Transactional(rollbackFor = Exception.class)

 

 

 

Transactional失效场景介绍

第一种 Transactional注解标注方法修饰符为非public时,@Transactional注解将会不起作用。

/**  
 **/  
@Component  
public class TestServiceImpl {  
    @Resource  
    TestMapper testMapper;  
      
    @Transactional  
    void insertTestWrongModifier() {  
        int re = testMapper.insert(new Test(10,20,30));  
        if (re > 0) {  
            throw new NeedToInterceptException("need intercept");  
        }  
        testMapper.insert(new Test(210,20,30));  
    }  
  

第二种

在类内部调用调用类内部@Transactional标注的方法。这种情况下也会导致事务不开启。

/**  
 **/  
@Component  
public class TestServiceImpl implements TestService {  
    @Resource  
    TestMapper testMapper;  
  
    @Transactional  
    public void insertTestInnerInvoke() {  
        //正常public修饰符的事务方法  
        int re = testMapper.insert(new Test(10,20,30));  
        if (re > 0) {  
            throw new NeedToInterceptException("need intercept");  
        }  
        testMapper.insert(new Test(210,20,30));  
    }  
  
  
    public void testInnerInvoke(){  
        //类内部调用@Transactional标注的方法。  
        insertTestInnerInvoke();  
    }  
  

 

第三种

事务方法内部捕捉了异常,没有抛出新的异常,导致事务操作不会进行回滚。

/**  
 **/  
@Component  
public class TestServiceImpl implements TestService {  
    @Resource  
    TestMapper testMapper;  
  
    @Transactional  
    public void insertTestCatchException() {  
        try {  
            int re = testMapper.insert(new Test(10,20,30));  
            if (re > 0) {  
                //运行期间抛异常  
                throw new NeedToInterceptException("need intercept");  
            }  
            testMapper.insert(new Test(210,20,30));  
        }catch (Exception e){  
            System.out.println("i catch exception");  
        }  
    }  
      
}  

 

@Transactional注解不起作用原理分析

第一种

@Transactional注解标注方法修饰符为非public时,@Transactional注解将会不起作用。这里分析 的原因是,@Transactional是基于动态代理实现的,@Transactional注解实现原理中分析了实现方法,在bean初始化过程中,对含有@Transactional标注的bean实例创建代理对象,这里就存在一个spring扫描@Transactional注解信息的过程,不幸的是源码中体现,标注@Transactional的方法如果修饰符不是public,那么就默认方法的@Transactional信息为空,那么将不会对bean进行代理对象创建或者不会对方法进行代理调用

@Transactional注解实现原理中,介绍了如何判定一个bean是否创建代理对象,大概逻辑是。根据spring创建好一个aop切点BeanFactoryTransactionAttributeSourceAdvisor实例,遍历当前bean的class的方法对象,判断方法上面的注解信息是否包含@Transactional,如果bean任何一个方法包含@Transactional注解信息,那么就是适配这个BeanFactoryTransactionAttributeSourceAdvisor切点。则需要创建代理对象,然后代理逻辑为我们管理事务开闭逻辑。

spring源码中,在拦截bean的创建过程,寻找bean适配的切点时,运用到下面的方法,目的就是寻找方法上面的@Transactional信息,如果有,就表示切点BeanFactoryTransactionAttributeSourceAdvisor能够应用(canApply)到bean中,

AopUtils#canApply(org.springframework.aop.Pointcut, java.lang.Class<?>, boolean)

public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {  
   Assert.notNull(pc, "Pointcut must not be null");  
   if (!pc.getClassFilter().matches(targetClass)) {  
      return false;  
   }  
  
   MethodMatcher methodMatcher = pc.getMethodMatcher();  
   if (methodMatcher == MethodMatcher.TRUE) {  
      // No need to iterate the methods if we're matching any method anyway...  
      return true;  
   }  
  
   IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;  
   if (methodMatcher instanceof IntroductionAwareMethodMatcher) {  
      introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;  
   }  
  
    //遍历class的方法对象  
   Set<Class<?>> classes = new LinkedHashSet<Class<?>>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));  
   classes.add(targetClass);  
   for (Class<?> clazz : classes) {  
      Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);  
      for (Method method : methods) {  
         if ((introductionAwareMethodMatcher != null &&  
               introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||  
             //适配查询方法上的@Transactional注解信息    
             methodMatcher.matches(method, targetClass)) {  
            return true;  
         }  
      }  
   }  
  
   return false;  
} 



第二种

在类内部调用调用类内部@Transactional标注的方法。这种情况下也会导致事务不开启。

既然事务管理是基于动态代理对象的代理逻辑实现的,那么如果在类内部调用类内部的事务方法,这个调用事务方法的过程并不是通过代理对象来调用的,而是直接通过this对象来调用方法,绕过的代理对象,肯定就是没有代理逻辑了。

实我们可以这样玩,内部调用也能实现开启事务,代码如下。

/**  
 * @author zhoujy  
 **/  
@Component  
public class TestServiceImpl implements TestService {  
    @Resource  
    TestMapper testMapper;  
  
    @Resource  
    TestServiceImpl testServiceImpl;  
  
  
    @Transactional  
    public void insertTestInnerInvoke() {  
        int re = testMapper.insert(new Test(10,20,30));  
        if (re > 0) {  
            throw new NeedToInterceptException("need intercept");  
        }  
        testMapper.insert(new Test(210,20,30));  
    }  
  
  
    public void testInnerInvoke(){  
        //内部调用事务方法  
        testServiceImpl.insertTestInnerInvoke();  
    }  
  
}  

第三种

事务方法内部捕捉了异常,没有抛出新的异常,导致事务操作不会进行回滚。

protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation)  
      throws Throwable {  
  
   // If the transaction attribute is null, the method is non-transactional.  
   final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);  
   final PlatformTransactionManager tm = determineTransactionManager(txAttr);  
   final String joinpointIdentification = methodIdentification(method, targetClass);  
  
   if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {  
      // Standard transaction demarcation with getTransaction and commit/rollback calls.  
       //开启事务  
      TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);  
      Object retVal = null;  
      try {  
         // This is an around advice: Invoke the next interceptor in the chain.  
         // This will normally result in a target object being invoked.  
          //反射调用业务方法  
         retVal = invocation.proceedWithInvocation();  
      }  
      catch (Throwable ex) {  
         // target invocation exception  
          //异常时,在catch逻辑中回滚事务  
         completeTransactionAfterThrowing(txInfo, ex);  
         throw ex;  
      }  
      finally {  
         cleanupTransactionInfo(txInfo);  
      }  
       //提交事务  
      commitTransactionAfterReturning(txInfo);  
      return retVal;  
   }  
  
   else {  
     //....................  
   }  
}  

所以看了上面的代码就一目了然了,事务想要回滚,必须能够在这里捕捉到异常才行,如果异常中途被捕捉掉,那么事务将不会回滚。

 
 
posted @   KLAPT  阅读(162)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2021-08-11 mysql 优化
点击右上角即可分享
微信分享提示