Spring管理事务默认回滚的异常是什么?

发布时间 2023-07-24 11:57:47作者: 迷走神经

问题:

Spring管理事务默认(即没有rollBackFor的情况下)可以回滚的异常是什么?

 

回答:

RuntimeException或者Error。

抛出运行时异常,是否回滚?Yes

@Transactional
public boolean rollbackOn(Throwable ex) {
    return new RuntimeException();
}

抛出错误,是否回滚? Yes

@Transactional
public void testTransationB(){
    throw new Error();
}

抛出非运行时异常,是否回滚? No

@Transactional
public void testTransationC() throws Exception{
    throw new Exception();
}

抛出非运行时异常,有rollBackFor=Exception.class的情况下,是否回滚? Yes

@Transactional(rollbackFor = Exception.class)
public void testTransationD() throws Exception{
    throw new Exception();
}

分析:

请看Spring源码类RuleBasedTransactionAttribute:

public boolean rollbackOn(Throwable ex) {
    if (logger.isTraceEnabled()) {
        logger.trace("Applying rules to determine whether transaction should rollback on " + ex);
    }
 
    RollbackRuleAttribute winner = null;
    int deepest = Integer.MAX_VALUE;
 
    if (this.rollbackRules != null) {
        for (RollbackRuleAttribute rule : this.rollbackRules) {
            int depth = rule.getDepth(ex);
            if (depth >= 0 && depth < deepest) {
                deepest = depth;
                winner = rule;
            }
        }
    }
 
    if (logger.isTraceEnabled()) {
        logger.trace("Winning rollback rule is: " + winner);
    }
 
    // User superclass behavior (rollback on unchecked) if no rule matches.
    if (winner == null) {
        logger.trace("No relevant rollback rule found: applying default rules");
        return super.rollbackOn(ex);
    }
        
    return !(winner instanceof NoRollbackRuleAttribute);
}

其中
ex:程序运行中抛出的异常,可以是Exception,RuntimeException,Error;

rollbackRules:代表rollBackFor指定的异常。默认情况下是empty。

所以默认情况下,winner等于null,程序调用super.rollbackOn(ex)

Here is the source code of super.rollbackOn(ex)

public boolean rollbackOn(Throwable ex) {
    return (ex instanceof RuntimeException || ex instanceof Error);
}

真相大白,结论是,默认情况下,如果是RuntimeException或Error的话,就返回True,表示要回滚,否则返回False,表示不回滚。

有rollBackFor的情况就不分析啦,这个也是可以触类旁通的。

 

转载:https://blog.csdn.net/lu930124/article/details/77596045