MyBatis事务管理源码阅读

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

Mybatis事务处理位于 org.apache.ibatis.transaction 下。类图如下:
在这里插入图片描述
入口类
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。关于这两个类的学习,以后再进行记录和分享。

一个平凡而普通的人,时时都会感到被生活的波涛巨浪所淹没。你会被淹没吗?除非你甘心沉沦 !!!

在这里插入图片描述
在这里插入图片描述

针对于上面的知识点我总结出了有1到5年开发经验的程序员在面试中涉及到的绝大部分架构面试题及答案做成了文档和架构视频资料免费分享给大家(包括Dubbo、Redis、Netty、zookeeper、Spring cloud、分布式、高并发等架构技术资料),希望能帮助到您面试前的复习且找到一个好的工作,也节省大家在网上搜索资料的时间来学习,也可以关注我一下以后会有更多干货分享。

扫描二维码关注公众号,回复: 5655395 查看本文章

资料获取方式 QQ群搜索“658752593” 备注“csdn” 即可免费领取

猜你喜欢

转载自blog.csdn.net/qq_42982923/article/details/88724969