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

转载连接:http://blog.csdn.net/u012557814/article/details/50685374

问题:

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

回答:

RuntimeException或者Error。

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

  1. @Transactional  
  2. public boolean rollbackOn(Throwable ex) {  
  3.     return new RuntimeException();  
  4. }  
抛出错误,是否回滚? Yes

  1. @Transactional  
  2. public void testTransationB(){  
  3.     throw new Error();  
  4. }  
抛出非运行时异常,是否回滚? No

  1. @Transactional  
  2. public void testTransationC() throws Exception{  
  3.     throw new Exception();  
  4. }  
抛出非运行时异常,有rollBackFor=Exception.class的情况下,是否回滚? Yes

  1. @Transactional(rollbackFor = Exception.class)  
  2. public void testTransationD() throws Exception{  
  3.     throw new Exception();  
  4. }  
分析:

请看Spring源码类RuleBasedTransactionAttribute:

  1. public boolean rollbackOn(Throwable ex) {  
  2.     if (logger.isTraceEnabled()) {  
  3.         logger.trace("Applying rules to determine whether transaction should rollback on " + ex);  
  4.     }  
  5.   
  6.     RollbackRuleAttribute winner = null;  
  7.     int deepest = Integer.MAX_VALUE;  
  8.   
  9.     if (this.rollbackRules != null) {  
  10.         for (RollbackRuleAttribute rule : this.rollbackRules) {  
  11.             int depth = rule.getDepth(ex);  
  12.             if (depth >= 0 && depth < deepest) {  
  13.                 deepest = depth;  
  14.                 winner = rule;  
  15.             }  
  16.         }  
  17.     }  
  18.   
  19.     if (logger.isTraceEnabled()) {  
  20.         logger.trace("Winning rollback rule is: " + winner);  
  21.     }  
  22.   
  23.     // User superclass behavior (rollback on unchecked) if no rule matches.  
  24.     if (winner == null) {  
  25.         logger.trace("No relevant rollback rule found: applying default rules");  
  26.         return super.rollbackOn(ex);  
  27.     }  
  28.           
  29.     return !(winner instanceof NoRollbackRuleAttribute);  
  30. }  
其中

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

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

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

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

  1. public boolean rollbackOn(Throwable ex) {  
  2.     return (ex instanceof RuntimeException || ex instanceof Error);  

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

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









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值