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

问题:

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的情况就不分析啦,这个也是可以触类旁通的。

  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值