1. 程式人生 > >Spring管理事務預設回滾的異常是什麼?

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的情況就不分析啦,這個也是可以觸類旁通的。