第08篇:Mybatis事务处理

蚀月继承
• 阅读 1005

一、Jdk底层实现

Java JDK中提供了标准接口Connection,不同的数据库驱动负责具体的实现。后面无论是Spring还是Mybatis对事务的处理,无论怎么的封装,最终究其到底都是由Connection来提供的能力。

public interface Connection  extends Wrapper, AutoCloseable {
    Statement createStatement() throws SQLException;
    void commit() throws SQLException;
    void rollback() throws SQLException;
}

例如 com.mysql.cj.jdbc.ConnectionImpl。具体负责跟mysql进行通信执行命令。

二、Mybatis实现

首先我们来看Mybatis是如何对Connection进行事务的封装。首先我们先来看一个图。

第08篇:Mybatis事务处理

2.1 调用流程

根据上面的图我们看,都是一层一层的封装进行委派最终由Connection的具体数据库驱动来进行实现的。

  • SqlSession
  • Executor
  • Transaction
public interface SqlSession extends Closeable {
  void commit();
  void rollback();
}
public interface Executor {
  void commit();
  void rollback();
}
public interface Transaction {
  void commit() throws SQLException;
  void rollback() throws SQLException;
}

2.2 实现原理

Mybatis中我们的接口是使用代理进行跟数据库进行交互的。所以他的事务提交逻辑是嵌套在代理方法中的。
通过前面的调用流程学习,第04篇:Mybatis代理对象生成我们知道最终都是在MapperMethod对SqlSession的调用执行数据库操作的。
而SqlSession是有两个包装类的。

  • SqlSession 通过底层的封装提供具体的调用指令
  • SqlSessionManager 对SqlSession进行代理,自动对事务进行处理
  • SqlSessionTemplate 事务的处理完全外包给Spring来处理

下面我们分别来看下每个类具体都做了什么吧。

SqlSessionManager

SqlSessionManager 是对SqlSession的一个包装,它会自己来管理SqlSession。他的具体实现是通过对SqlSession
生成代理,代理拦截每个方法进行增强。


  private SqlSessionManager(SqlSessionFactory sqlSessionFactory) {
    this.sqlSessionFactory = sqlSessionFactory;
    this.sqlSessionProxy = (SqlSession) Proxy.newProxyInstance(
        SqlSessionFactory.class.getClassLoader(),
        new Class[]{SqlSession.class},
        new SqlSessionInterceptor());
  }

SqlSessionInterceptor

 private class SqlSessionInterceptor implements InvocationHandler {
    public SqlSessionInterceptor() {
        // Prevent Synthetic Access
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      final SqlSession sqlSession = SqlSessionManager.this.localSqlSession.get();
      if (sqlSession != null) {
        try {
          return method.invoke(sqlSession, args);
        } catch (Throwable t) {
          throw ExceptionUtil.unwrapThrowable(t);
        }
      } else {
        try (SqlSession autoSqlSession = openSession()) {
          try {
            final Object result = method.invoke(autoSqlSession, args);
            autoSqlSession.commit();
            return result;
          } catch (Throwable t) {
            autoSqlSession.rollback();
            throw ExceptionUtil.unwrapThrowable(t);
          }
        }
      }
    }
  }
  1. 从ThreadLocal中获取SqlSession,如果有,说明是调用方要自己处理事务,那么就只进行执行数据库操作,不进行事务处理和连接的关闭。
  2. 如果没有,说明要自己来管理事务,那么就新生成SqlSession,帮我们调用SqlSession#commit来提交事务,失败进行回滚。

根据其中原理我们知道有两种使用办法,

  • 首先第一种自己管理SqlSession的方式
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    // 实例化sqlSessionManager
    SqlSessionManager sqlSessionManager = SqlSessionManager.newInstance(inputStream);
    // 第一步: 开启管理SqlSession,创建一个SqlSession并存入到ThreadLocal中
    sqlSessionManager.startManagedSession();
    // 使用
    UserMapper mapper = sqlSessionManager.getMapper(UserMapper.class);
    mapper.save(new User("孙悟空"));
    // 第二步: 因为事务是我们自己开启的,所以要自己来操作提交事务,或者回滚
    sqlSessionManager.commit();
    // 第三步: 关闭连接
    sqlSessionManager.close();
  • 第二种,自动管理SqlSession
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    // 实例化sqlSessionManager
    SqlSessionManager sqlSessionManager = SqlSessionManager.newInstance(inputStream);
    UserMapper mapper = sqlSessionManager.getMapper(UserMapper.class);
    mapper.save(new User("孙悟空"));
    // 只用关心关闭就好了,事务的信息,都帮我们完成了。
    sqlSessionManager.close();

SqlSessionTemplate

线程安全、Spring 管理、与 Spring 事务管理一起使用的SqlSession ,以确保实际使用的 SqlSession 是与当前 Spring 事务关联的那个。此外,它还管理会话生命周期,包括根据 Spring 事务配置根据需要关闭、提交或回滚会话。
模板需要一个 SqlSessionFactory 来创建 SqlSession,作为构造函数参数传递。也可以构造指示要使用的执行器类型,如果没有,将使用会话工厂中定义的默认执行器类型。
此模板将 MyBatis PersistenceExceptions 转换为未经检查的 DataAccessExceptions,默认情况下使用MyBatisExceptionTranslator 。

==SqlSessionTemplate== 和 ==SqlSessionManager==

  • 相同点: 都是通过对SqlSession进行代理对方法进行增强的
  • 不同点: 前者是将SqlSession外包给Spring进行管理的,后者是自己通过ThreadLocal进行管理的。

下面我们来具体看下是如何拦截增强的。

  1. 第一个点获取SqlSession不同。

    • 从Spring中的事务管理器中获取当前线程的事务信息
  2. 第二个点方法执行完成后都会自动关闭SqlSession或减少引用

    • 为解决嵌套事务的情况,每次执行完后会减少一次引用。当引用都减少为0才会真正进行关闭。
  3. 第三个点是否提交事务,有判定规则。

    • 只有Spring事务管理器中没有事务时候才会自己进行提交,否则都外包给Spring进行管理。

下面我们具体来看下代码的实现吧。

 private class SqlSessionInterceptor implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      SqlSession sqlSession = getSqlSession(SqlSessionTemplate.this.sqlSessionFactory,
          SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator);
      try {
        Object result = method.invoke(sqlSession, args);
        if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
          // force commit even on non-dirty sessions because some databases require
          // a commit/rollback before calling close()
          sqlSession.commit(true);
        }
        return result;
      } catch (Throwable t) {
        Throwable unwrapped = unwrapThrowable(t);
        if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
          // release the connection to avoid a deadlock if the translator is no loaded. See issue #22
          closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
          sqlSession = null;
          Throwable translated = SqlSessionTemplate.this.exceptionTranslator
              .translateExceptionIfPossible((PersistenceException) unwrapped);
          if (translated != null) {
            unwrapped = translated;
          }
        }
        throw unwrapped;
      } finally {
        if (sqlSession != null) {
          closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
        }
      }
    }
  }

getSqlSession

  • 从Spring提供的事务管理器(TransactionSynchronizationManager)中获取当前线程拥有的SqlSession
  • 如果没有就新建一个并注册到TransactionSynchronizationManager上。
 public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
      PersistenceExceptionTranslator exceptionTranslator) {

    notNull(sessionFactory, NO_SQL_SESSION_FACTORY_SPECIFIED);
    notNull(executorType, NO_EXECUTOR_TYPE_SPECIFIED);
    // 从Spring提供的事务管理器(TransactionSynchronizationManager)中获取当前线程拥有的SqlSession
    // 逻辑很简单key=SqlSessionFactory value=SqlSessionHolder
    SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);

    SqlSession session = sessionHolder(executorType, holder);
    if (session != null) {
      return session;
    }

    LOGGER.debug(() -> "Creating a new SqlSession");
    session = sessionFactory.openSession(executorType);
    // 如果没有就新建一个并注册到TransactionSynchronizationManager上。
    registerSessionHolder(sessionFactory, executorType, exceptionTranslator, session);

    return session;
  }

registerSessionHolder

  • 为了保险先判断下当前线程中是否已经存在同步器,如果存在还注册就提示: "SqlSession [" + session + "] was not registered for synchronization because synchronization is not active");
  • 如果当前线程没有,判断事务管理器是否是SpringManagedTransactionFactory,如果是就注册一个。
  • SqlSessionHolder#requested() 注意这一行,创建后给引用次数加1.
private static void registerSessionHolder(SqlSessionFactory sessionFactory, ExecutorType executorType,
      PersistenceExceptionTranslator exceptionTranslator, SqlSession session) {
    SqlSessionHolder holder;
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
      Environment environment = sessionFactory.getConfiguration().getEnvironment();

      if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) {
        LOGGER.debug(() -> "Registering transaction synchronization for SqlSession [" + session + "]");

        holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
        TransactionSynchronizationManager.bindResource(sessionFactory, holder);
        TransactionSynchronizationManager
            .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
        holder.setSynchronizedWithTransaction(true);
        holder.requested();
      } else {
        if (TransactionSynchronizationManager.getResource(environment.getDataSource()) == null) {
          LOGGER.debug(() -> "SqlSession [" + session
              + "] was not registered for synchronization because DataSource is not transactional");
        } else {
          throw new TransientDataAccessResourceException(
              "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
        }
      }
    } else {
      LOGGER.debug(() -> "SqlSession [" + session
          + "] was not registered for synchronization because synchronization is not active");
    }

closeSqlSession

  • 如果是Spring的事务管理,就减少引用
  • 如果不是Spring的事务管理,就直接关闭
  public static void closeSqlSession(SqlSession session, SqlSessionFactory sessionFactory) {
    notNull(session, NO_SQL_SESSION_SPECIFIED);
    notNull(sessionFactory, NO_SQL_SESSION_FACTORY_SPECIFIED);

    SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if ((holder != null) && (holder.getSqlSession() == session)) {
      LOGGER.debug(() -> "Releasing transactional SqlSession [" + session + "]");
      holder.released();
    } else {
      LOGGER.debug(() -> "Closing non transactional SqlSession [" + session + "]");
      session.close();
    }
  }

isSqlSessionTransactional

事务的判定逻辑:

  • 如果从事务管理器中获取,说明当前线程是有事务的
  • 当前线程中的事务SqlSession和这个方法中的SqlSession是同一个,说明是嵌套事务。

如果是Spring来管理事务,这就不会自动来提交事务。外包给Spring的事务拦截器自己去处理。

  public static boolean isSqlSessionTransactional(SqlSession session, SqlSessionFactory sessionFactory) {
    notNull(session, NO_SQL_SESSION_SPECIFIED);
    notNull(sessionFactory, NO_SQL_SESSION_FACTORY_SPECIFIED);

    SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);

    return (holder != null) && (holder.getSqlSession() == session);
  }

好了,到这里Mybatis中事务的处理逻辑我们就到了解了。

SqlSession对底层进行封装提供具体的指令
SqlSessionManager和SqlSessionTemplate都是对SqlSession进行增强来自动或者委派Spring进行事务的处理的。

下面我们去看看Spring是如何来处理事务的吧。Spring事务的处理方式

感谢您的阅读,本文由 西魏陶渊明 版权所有。如若转载,请注明出处:西魏陶渊明(https://blog.springlearn.cn/)

本文由mdnice多平台发布

点赞
收藏
评论区
推荐文章
代码哈士奇 代码哈士奇
4年前
uni-app使用uniCloud时做类似于拦截器和请求结果再处理(类似于请求和响应拦截)
想要在使用uniCloud的使用拦截请求怎么办再次封装uniCloud.callFunction特别说明这里的token是我自己存储成token如果你使用了uniid官方的推荐是('uniidtoken')('uniidtokenexpired')存储了uniidtoken后请求会自动携带这里的res.result.code0是因为我的云
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Easter79 Easter79
3年前
sql:mysql:函数:TIMESTAMPDIFF函数实现TimeStamp字段相减,求得时间差
<divclass"htmledit\_views"id"content\_views"<p&nbsp;函数内指定是minute,则最终结果value值的单位是分钟,如果函数内指定为hours,则最终结果value值单位为小时。</p<preclass"has"name"code"<codeclass"hljssql"<
Stella981 Stella981
3年前
Linux自动检测网站心跳通知shell脚本
!/bin/bashLIST("http://xxxx.com")NAME("评价系统getwindowList接口")for((i0;i<${LIST@};i))doHTTP_CODEcurlo/dev/nullsw"%{http_code}""${LIST
Stella981 Stella981
3年前
MyBatis使用自定义TypeHandler转换类型
MyBatis虽然有很好的SQL执行性能,但毕竟不是完整的ORM框架,不同的数据库之间SQL执行还是有差异。笔者最近在升级Oracle驱动至ojdbc7,就发现了处理DATE类型存在问题。还好MyBatis提供了使用自定义TypeHandler转换类型的功能。本文介绍如下使用TypeHandler实现日期类型的转换。问题背景
Wesley13 Wesley13
3年前
MySQL数据库InnoDB存储引擎Log漫游(1)
作者:宋利兵来源:MySQL代码研究(mysqlcode)0、导读本文介绍了InnoDB引擎如何利用UndoLog和RedoLog来保证事务的原子性、持久性原理,以及InnoDB引擎实现UndoLog和RedoLog的基本思路。00–UndoLogUndoLog是为了实现事务的原子性,
Stella981 Stella981
3年前
PowerDesigner列名、注释内容互换
在用PowerDesigner时,常常在NAME或Comment中写中文在Code中写英文,Name只会显示给我们看,Code会使用在代码中,但Comment中的文字会保存到数据库TABLE的Description中,有时候我们写好了Name再写一次Comment很麻烦,以下两段代码就可以解决这个问题。在PowerDesigner中PowerDesig
Easter79 Easter79
3年前
SwiftUI 跨组件数据传递
作者:Cyandev,iOS和MacOS开发者,目前就职于字节跳动0x00前言众所周知,SwiftUI的开发模式与React、Flutter非常相似,即都是声明式UI,由数据驱动(产生)视图,视图也会与数据自动保持同步,框架层会帮你处理“绑定”的问题。在声明式UI中不存在命令式地让一个视图变成xxx
Wesley13 Wesley13
3年前
MySQL数据库存储引擎概述
一、前言引擎(Engine),我们都知道是机器发动机的核心所在,数据库存储引擎便是数据库的底层软件组织。数据库使用数据存储引擎实现存储、处理和保护数据的核心服务。利用数据库引擎可控制访问权限并快速处理事务,从而满足企业内大多数需要处理大量数据的应用程序的要求。使用数据库引擎创建用于联机事务处理或联机分析处理数据的关系数据库。这
Stella981 Stella981
3年前
MyBatis在Spring环境下的事务管理
MyBatis的设计思想很简单,可以看做是对JDBC的一次封装,并提供强大的动态SQL映射功能。但是由于它本身也有一些缓存、事务管理等功能,所以实际使用中还是会碰到一些问题——另外,最近接触了JFinal,其思想和Hibernate类似,但要更简洁,和MyBatis的设计思想不同,但有一点相同:都是想通过简洁的设计最大限度地简化开发和提升性能——说到性能,前
MySQL事务死锁问题排查 | 京东云技术团队
一、背景在预发环境中,由消息驱动最终触发执行事务来写库存,但是导致MySQL发生死锁,写库存失败。com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException:rpcerror:code
蚀月继承
蚀月继承
Lv1
出师未捷身先死,长使英雄泪满襟。
文章
5
粉丝
0
获赞
0