注意tips-spring事务控制默认回滚条件

最近遇到个case,在事务控制下insert,过程中会发生http API调用,发生任何异常情况,直接回滚。

然而,http 连接timeout的情况下,insert 却成功了。

一直以为只要throw Exception,默认事务就会回滚,看了源码,才纠正了这个误解。

......

处理异常的实现:

/**
 * Handle a throwable, completing the transaction.
 * We may commit or roll back, depending on the configuration.
 */
protected void completeTransactionAfterThrowing(TransactionInfo txInfo, Throwable ex) {
    if (txInfo != null && txInfo.hasTransaction()) {
        // 哪种Exception 会触发rollback ???
        if (txInfo.transactionAttribute.rollbackOn(ex)) {
            try {
                txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
            }
            // ...
        } else {
            // We don't roll back on this exception. 呃,还是会commit!!!
            // Will still roll back if TransactionStatus.isRollbackOnly() is true.
            try {
                txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
            }
            // ...
    	}
    }
}
......

再看看哪种Exception会触发rollback

/**
 * The default behavior is as with EJB: rollback on unchecked exception.
 * Additionally attempt to rollback on Error.
 * TransactionTemplate 默认支持.
 */
public boolean rollbackOn(Throwable ex) {
    return (ex instanceof RuntimeException || ex instanceof Error);
}
......

上述的情况怎么处理:

try...catch(ex) {打印error日志 && throw RuntimeException(...)}

......

总结:

默认事务回滚策略:throw RuntimeException 或者 Error

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值