spring提交事务源码分析

1,499 阅读2分钟

核心类

类继承图

1.PlatformTransactionManager
接口定义了提交事务的方法

2.AbstractPlatformTransactionManager
抽象类实现了提交事务的方法,但是真正的实现是交给了orm框架的事务管理器

3.orm框架-事务管理器
提交事务方法的真正实现,再底层就是数据库连接池,最后是jdbc客户端的连接实现类。

抽象类AbstractPlatformTransactionManager

提交事务

public abstract class AbstractPlatformTransactionManager implements PlatformTransactionManager, Serializable {

public final void commit(TransactionStatus status) throws TransactionException {
  if (status.isCompleted()) {
    throw new IllegalTransactionStateException("Transaction is already completed - do not call commit or rollback more than once per transaction");
  } else {
    DefaultTransactionStatus defStatus = (DefaultTransactionStatus)status;
    if (defStatus.isLocalRollbackOnly()) {
      if (defStatus.isDebug()) {
        this.logger.debug("Transactional code has requested rollback");
      }

      this.processRollback(defStatus);
    } else if (!this.shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
      if (defStatus.isDebug()) {
        this.logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
      }

      this.processRollback(defStatus);
      if (status.isNewTransaction() || this.isFailEarlyOnGlobalRollbackOnly()) {
        throw new UnexpectedRollbackException("Transaction rolled back because it has been marked as rollback-only");
      }
    } else {
      this.processCommit(defStatus); //处理事务
    }
  }
}

private void processCommit(DefaultTransactionStatus status) throws TransactionException {
  try {
    boolean beforeCompletionInvoked = false;

    try {
      this.prepareForCommit(status);
      this.triggerBeforeCommit(status);
      this.triggerBeforeCompletion(status);
      beforeCompletionInvoked = true;
      boolean globalRollbackOnly = false;
      if (status.isNewTransaction() || this.isFailEarlyOnGlobalRollbackOnly()) {
        globalRollbackOnly = status.isGlobalRollbackOnly();
      }

      if (status.hasSavepoint()) {
        if (status.isDebug()) {
          this.logger.debug("Releasing transaction savepoint");
        }

        status.releaseHeldSavepoint();
      } else if (status.isNewTransaction()) {
        if (status.isDebug()) {
          this.logger.debug("Initiating transaction commit");
        }

        this.doCommit(status); //提交事务(抽象方法)
      }

      if (globalRollbackOnly) {
        throw new UnexpectedRollbackException("Transaction silently rolled back because it has been marked as rollback-only");
      }
    } catch (UnexpectedRollbackException var19) {
      this.triggerAfterCompletion(status, 1);
      throw var19;
    } catch (TransactionException var20) {
      if (this.isRollbackOnCommitFailure()) {
        this.doRollbackOnCommitException(status, var20);
      } else {
        this.triggerAfterCompletion(status, 2);
      }

      throw var20;
    } catch (RuntimeException var21) {
      if (!beforeCompletionInvoked) {
        this.triggerBeforeCompletion(status);
      }

      this.doRollbackOnCommitException(status, var21);
      throw var21;
    } catch (Error var22) {
      if (!beforeCompletionInvoked) {
        this.triggerBeforeCompletion(status);
      }

      this.doRollbackOnCommitException(status, var22);
      throw var22;
    }

    try {
      this.triggerAfterCommit(status);
    } finally {
      this.triggerAfterCompletion(status, 0);
    }
  } finally {
    this.cleanupAfterCompletion(status); //释放资源,比如归还连接到连接池
  }

}

private void cleanupAfterCompletion(DefaultTransactionStatus status) {
  status.setCompleted();
  if (status.isNewSynchronization()) {
    TransactionSynchronizationManager.clear();
  }

  if (status.isNewTransaction()) {
    this.doCleanupAfterCompletion(status.getTransaction()); //释放资源,比如归还连接到连接池 (抽象方法)
  }

  if (status.getSuspendedResources() != null) {
    if (status.isDebug()) {
      this.logger.debug("Resuming suspended transaction after completion of inner transaction");
    }

    this.resume(status.getTransaction(), (AbstractPlatformTransactionManager.SuspendedResourcesHolder)status.getSuspendedResources());
  }

}

1.提交事务 2.释放资源 这两个方法都是抽象方法,所以都是调用底层的orm框架去实现的,比如Hibernate事务管理器。

Hibernate事务管理器

public class HibernateTransactionManager extends AbstractPlatformTransactionManager implements ResourceTransactionManager, BeanFactoryAware, InitializingBean {

protected void doCommit(DefaultTransactionStatus status) {
  HibernateTransactionManager.HibernateTransactionObject txObject = (HibernateTransactionManager.HibernateTransactionObject)status.getTransaction();
  if (status.isDebug()) {
    this.logger.debug("Committing Hibernate transaction on Session [" + SessionFactoryUtils.toString(txObject.getSessionHolder().getSession()) + "]");
  }

  try {
    txObject.getSessionHolder().getTransaction().commit(); //提交事务
  } catch (TransactionException var4) {
    throw new TransactionSystemException("Could not commit Hibernate transaction", var4);
  } catch (HibernateException var5) {
    throw this.convertHibernateAccessException(var5);
  }
}
public void commit() throws HibernateException {
  if (!this.begun) {
    throw new TransactionException("Transaction not successfully started");
  } else {
    log.debug("commit");
    if (!this.transactionContext.isFlushModeNever() && this.callback) {
      this.transactionContext.managedFlush();
    }

    this.notifySynchronizationsBeforeTransactionCompletion();
    if (this.callback) {
      this.jdbcContext.beforeTransactionCompletion(this);
    }

    try {
      this.commitAndResetAutoCommit(); //提交事务
      log.debug("committed JDBC Connection");
      this.committed = true;
      if (this.callback) {
        this.jdbcContext.afterTransactionCompletion(true, this);
      }

      this.notifySynchronizationsAfterTransactionCompletion(3);
    } catch (SQLException var6) {
      log.error("JDBC commit failed", var6);
      this.commitFailed = true;
      if (this.callback) {
        this.jdbcContext.afterTransactionCompletion(false, this);
      }

      this.notifySynchronizationsAfterTransactionCompletion(5);
      throw new TransactionException("JDBC commit failed", var6);
    } finally {
      this.closeIfRequired();
    }

  }
}

private void commitAndResetAutoCommit() throws SQLException {
  try {
    this.jdbcContext.connection().commit(); //提交事务:通过连接池里的数据库连接来提交事务
  } finally {
    this.toggleAutoCommit();
  }

}

数据库连接池

1.dbcp

public class DelegatingConnection extends AbandonedTrace implements Connection {

public void commit() throws SQLException {
  this.checkOpen();

  try {
    this._conn.commit(); //提交事务:通过jdbc连接来提交事务
  } catch (SQLException var2) {
    this.handleException(var2);
  }

}

2.druid

public class DruidPooledConnection extends PoolableWrapper implements PooledConnection, Connection {

public void commit() throws SQLException {
  this.checkState();
  DruidAbstractDataSource dataSource = this.holder.getDataSource();
  dataSource.incrementCommitCount();

  try {
    this.conn.commit();//提交事务:通过jdbc连接来提交事务
  } catch (SQLException var6) {
    this.handleException(var6);
  } finally {
    this.handleEndTransaction(dataSource, (Savepoint)null);
  }

}

再底层,也是最后的底层,就是jdbc客户端的连接对象Connection实现,比如OracleConnection

方法调用栈

1.业务事务方法开始 //spring事务拦截器
2.业务sql1/sql
3.业务方法结束

4.提交事务 //spring事务拦截器

5.spring的事务管理器
抽象类

6.orm框架的事务管理器
比如Hibernate事务管理器

7.数据库连接池

8.jdbc客户端
实现了jdbc api里的Connection,比如OracleConnection。

参考

zhuanlan.zhihu.com/p/54067384 zhuanlan.zhihu.com/p/54067384