详解Spring事务回滚和事务提交
回滚逻辑如下:
判断是否存在事务,只有存在事务才执行回滚 根据异常类型判断是否回滚。如果异常类型不符合,仍然会提交事务 回滚处理详细解析
判断是否存在事务,只有存在事务才执行回滚,即是否有@Transactional事务注解或相关事务切面 根据异常类型判断是否回滚。如果异常类型不符合,仍然会提交事务根据@Transactional注解中rollbackFor、rollbackForClassName、noRollbackForClassName配置的值,找到最符合ex的异常类型,如果符合的异常类型不是NoRollbackRuleAttribute,则可以执行回滚。如果@Transactional没有配置,则默认使用RuntimeException和Error异常。代码如下:
@Overridepublic 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; //rollbackRules保存@Transactional注解中rollbackFor、rollbackForClassName、noRollbackForClassName配置的值 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. //若@Transactional没有配置,默认调用父类的 if (winner == null) { logger.trace('No relevant rollback rule found: applying default rules'); return super.rollbackOn(ex); } return !(winner instanceof NoRollbackRuleAttribute);}//super@Overridepublic boolean rollbackOn(Throwable ex) { return (ex instanceof RuntimeException || ex instanceof Error);}
回滚处理
如果存在安全点,则回滚事务至安全点,这个主要是处理嵌套事务,回滚安全点的操作还是交给了数据库处理. 当前事务是一个新事务时,那么直接回滚,使用的是DataSourceTransactionManager事务管理器,所以调用DataSourceTransactionManager#doRollback,直接调用数据库连接的回滚方法。 当前存在事务,但又不是一个新的事务,只把事务的状态标记为read-only,等到事务链执行完毕后,统一回滚,调用DataSourceTransactionManager#doSetRollbackOnly 清空记录的资源并将挂起的资源恢复代码如下:
private void processRollback(DefaultTransactionStatus status) { try { try { triggerBeforeCompletion(status); //如果有安全点,回滚至安全点 if (status.hasSavepoint()) { if (status.isDebug()) { logger.debug('Rolling back transaction to savepoint'); } status.rollbackToHeldSavepoint(); } //如果是新事务,回滚事务 else if (status.isNewTransaction()) { if (status.isDebug()) { logger.debug('Initiating transaction rollback'); } doRollback(status); } //如果有事务但不是新事务,则把标记事务状态,等事务链执行完毕后统一回滚 else if (status.hasTransaction()) { if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) { if (status.isDebug()) { logger.debug('Participating transaction failed - marking existing transaction as rollback-only'); } doSetRollbackOnly(status); } else { if (status.isDebug()) { logger.debug('Participating transaction failed - letting transaction originator decide on rollback'); } } } else { logger.debug('Should roll back transaction but cannot - no transaction available'); } } catch (RuntimeException ex) { triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN); throw ex; } catch (Error err) { triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN); throw err; } triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK); } finally { //清空记录的资源并将挂起的资源恢复 cleanupAfterCompletion(status); }}事务提交
事务提交逻辑如下:
判断事务是否已经完成,如果完成抛出异常 判断事务是否已经被标记成回滚,则执行回滚操作 嵌入事务标记回滚,如果嵌入事务抛出了异常执行了回滚,但是在调用方把嵌入事务的异常个捕获没有抛出,就会执行这一步。 提交事务代码如下:
@Overridepublic final void commit(TransactionStatus status) throws TransactionException { //1. 判断事务是不是已经完成 if (status.isCompleted()) { throw new IllegalTransactionStateException( 'Transaction is already completed - do not call commit or rollback more than once per transaction'); } DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status; //2. 如果在事务链中已经被标记回滚,那么不会尝试提交事务,直接回滚,不过我没找到在哪设置这个值 if (defStatus.isLocalRollbackOnly()) { if (defStatus.isDebug()) { logger.debug('Transactional code has requested rollback'); } processRollback(defStatus); return; } //3. shouldCommitOnGlobalRollbackOnly()默认返回false,isGlobalRollbackOnly是在嵌入事务回滚的时候赋值的 if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) { if (defStatus.isDebug()) { logger.debug('Global transaction is marked as rollback-only but transactional code requested commit'); } processRollback(defStatus); // Throw UnexpectedRollbackException only at outermost transaction boundary // or if explicitly asked to. if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) { throw new UnexpectedRollbackException( 'Transaction rolled back because it has been marked as rollback-only'); } return; } //4. 提交事务 processCommit(defStatus);}
以上就是详解Spring事务回滚和事务提交的详细内容,更多关于Spring事务回滚和事务提交的资料请关注好吧啦网其它相关文章!
相关文章: