MyBatis事务管理源码阅读

2022-09-23 13:06:50

在实际的开发工作中,MyBatis已经成为了当下最流行的关系型数据库与实体Model的映射框架。
今天就简单学习一下MyBatis的事务处理部分源码。

Mybatis事务处理位于 org.apache.ibatis.transaction 下。类图如下:
MyBatis事务类图

入口类:
Transaction

Wraps a database connection. Handles the connection lifecycle that comprises: its creation, preparation, commit/rollback and close.

接口中定义的方法详解

  1. Connection getConnection() 获取数据库连接
  2. void commit() 事务提交
  3. void rollback() 事务回滚
  4. void close() 关闭连接
  5. Integer getTimeout() 获取超时时间设置

再来看一下,TransactionFactory,显然它是创建Transaction的工厂类。

  1. void setProperties(Properties props);
  2. Transaction newTransaction(Connection conn);
  3. Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit);

Transaction有两个实现类,分别是JdbcTransactionManagedTransaction,前者是原生的事务生命周期处理类,而后者是由容器来管理事务的生命周期。这里所指的容器是指Spring或者是Tomcat。

Connection对象是通过DataSource来获取的,同时会设置数据库事务的隔离级别TransactionIsolationLevel

protected void openConnection() throws SQLException {

    if (log.isDebugEnabled()) {
      log.debug("Opening JDBC Connection");
    }

    this.connection = this.dataSource.getConnection();
    if (this.level != null) {
      this.connection.setTransactionIsolation(this.level.getLevel());
    }

}

TransactionIsolationLevel是一个枚举类,维护了一个final类型的int值,来抽象数据库事务的四个级别。

/**
    事务隔离级别
*/
public enum TransactionIsolationLevel {
  NONE(Connection.TRANSACTION_NONE),                                            //1.none   不要求事务管理     0
  READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED),                        //2.read_committed   已提交读  1
  READ_UNCOMMITTED(Connection.TRANSACTION_READ_UNCOMMITTED),                    //3 .read_uncomittted  未提交读  2
  REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ),                      //4.repeatable_read  可重复读   4
  SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE);                            // 5.sealalizable  可串行化    8

  private final int level;

  private TransactionIsolationLevel(int level) {
    this.level = level;
  }

  public int getLevel() {
    return level;
  }
}

在事务处理过程中,还有两个不可或缺的重要角色,ConnectionDataSource。关于这两个类的学习,以后再进行记录和分享。

BTW,这是我的第一篇博文,这篇文章也是对Markdown语法的学习。


  • 作者:weixin_30821731
  • 原文链接:https://blog.csdn.net/weixin_30821731/article/details/97507699
    更新时间:2022-09-23 13:06:50