mybatis对事务的管理

Posted jas0

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis对事务的管理相关的知识,希望对你有一定的参考价值。

1、在获取一个session的时候会从tranactionFactory实例化一个对象放到session的属性中

  public SqlSession openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }
   private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      final Environment environment = configuration.getEnvironment();
      // 从environment 这里就两种一个是JdbcTransaction 一个是 ManagedTransaction
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      // 获取一个事务
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

2、什么时候开启事务呢?

 // BaseExcutor 中获取connection时会调用事务的getConnection方法
 protected Connection getConnection(Log statementLog) throws SQLException {
    Connection connection = transaction.getConnection();
    if (statementLog.isDebugEnabled()) {
      return ConnectionLogger.newInstance(connection, statementLog, queryStack);
    } else {
      return connection;
    }
  }
  //transaction.getConnection
  public Connection getConnection() throws SQLException {
    if (connection == null) {
      openConnection();
    }
    return connection;
  }
  // openConnection
   protected void openConnection() throws SQLException {
    if (log.isDebugEnabled()) {
      log.debug("Opening JDBC Connection");
    }
    connection = dataSource.getConnection();
    if (level != null) {
      // 设置隔离级别
      connection.setTransactionIsolation(level.getLevel());
    }
    // 是否关闭自动提交事务
    setDesiredAutoCommit(autoCommmit);
  }

3、什么时候提交或者关闭事务呢?

 // Session.close()
 public void close() {
    try {
      executor.close(isCommitOrRollbackRequired(false));
      dirty = false;
    } finally {
      ErrorContext.instance().reset();
    }
  }
  // CachingExcutor.close()
  public void close(boolean forceRollback) {
    try {
      //issues #499, #524 and #573
      if (forceRollback) { 
          //事务的回滚
        tcm.rollback();
      } else {
          //事务的提交
        tcm.commit();
      }
    } finally {
      delegate.close(forceRollback);
    }
  }

 

以上是关于mybatis对事务的管理的主要内容,如果未能解决你的问题,请参考以下文章

mybatis对事务的管理

MyBatis事务管理机制

mybatis深入理解-----MyBatis事务管理机制

mybatis事务管理机制详解

详解 MyBatis 事务管理,彻底颠覆你对事务的理解!

详解 MyBatis 事务管理,彻底颠覆你对事务的理解!