zoukankan      html  css  js  c++  java
  • mybatis源码分析(3)-----SqlSessionHolder作用

    1、 sqlSessionHolder 是位于mybatis-spring 包下面,他的作用是对于sqlSession和事务的控制

    • sqlSessionHolder 继承了spring的ResourceHolderSupport
    public abstract class ResourceHolderSupport implements ResourceHolder {
        //事务是否开启 
       private boolean synchronizedWithTransaction = false; private boolean rollbackOnly = false; private Date deadline;
    // 引用次数 private int referenceCount = 0; private boolean isVoid = false; }

    2 、在前面讲解到,sqlSessionTemplate 操作数据库实际操作是对于代理对象 目标方法的执行。

    •  代理对象是如何获取defaultSqlSession ,在代理方法中通过SqlSessionUtils 的方法获取SqlSession
    •   它会首先获取SqlSessionHolder,SqlSessionHolder用于在TransactionSynchronizationManager中保持当前的SqlSession。
    •   如果holder不为空,并且holder被事务锁定,则可以通过holder.getSqlSession()方法,从当前事务中获取sqlSession,即 Fetched SqlSession from current transaction。
    •   如果不存在holder或没有被事务锁定,则会创建新的sqlSession,即 Creating a new SqlSession,通过sessionFactory.openSession()方法。
    •   如果当前线程的事务是活跃的,将会为SqlSession注册事务同步,即 Registering transaction synchronization for SqlSession。
      public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {
       //从从前线程的threadLocal 中获取sqlSessionHolder SqlSessionHolder holder
    = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    //调用静态方法sessionHoler 判断是否存在符合要求的sqlSession SqlSession session
    = sessionHolder(executorType, holder);
       // 判断当前sqlSessionHolder 中是否持有sqlSession (即当前操作是否在事务当中)
    if (session != null) {
        //如果持有sqlSesison 的引用,则直接获取
    return session; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Creating a new SqlSession"); } //获取新的sqlSession 对象。这里由sessionFacory产生的defaultSqlSession session = sessionFactory.openSession(executorType);
    //判断判断,当前是否存在事务,将sqlSession 绑定到sqlSessionHolder 中,并放到threadLoacl 当中 registerSessionHolder(sessionFactory, executorType, exceptionTranslator, session);
    return session; }
    •   private static SqlSession sessionHolder(ExecutorType executorType, SqlSessionHolder holder) {
          SqlSession session = null;
          if (holder != null && holder.isSynchronizedWithTransaction()) {
      //hodler保存的执行类型和获取SqlSession的执行类型不一致,就会抛出异常,也就是说在同一个事务中,执行类型不能变化,原因就是同一个事务中同一个sqlSessionFactory创建的sqlSession会被重用 
      if (holder.getExecutorType() != executorType) { throw new TransientDataAccessResourceException("Cannot change the ExecutorType when there is an existing transaction"); } //增加该holder,也就是同一事务中同一个sqlSessionFactory创建的唯一sqlSession,其引用数增加,被使用的次数增加  holder.requested(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction"); } //返回sqlSession  session = holder.getSqlSession(); } return session; }
    • 注册的方法如下
      private static void registerSessionHolder(SqlSessionFactory sessionFactory, ExecutorType executorType,
          PersistenceExceptionTranslator exceptionTranslator, SqlSession session) {
        SqlSessionHolder holder;
       //判断事务是否存在
    if (TransactionSynchronizationManager.isSynchronizationActive()) { Environment environment = sessionFactory.getConfiguration().getEnvironment(); //加载环境变量,判断注册的事务管理器是否是SpringManagedTransaction,也就是Spring管理事务 if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registering transaction synchronization for SqlSession [" + session + "]"); } holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
       //如果当前回话处在事务当中,则将holder 绑定到ThreadLocal 中
    //以sessionFactory为key,hodler为value,加入到TransactionSynchronizationManager管理的本地缓存ThreadLocal<Map<Object, Object>> resources中  TransactionSynchronizationManager.bindResource(sessionFactory, holder);
    //将holder, sessionFactory的同步加入本地线程缓存中ThreadLocal<Set<TransactionSynchronization>> synchronizations  TransactionSynchronizationManager.registerSynchronization(
    new SqlSessionSynchronization(holder, sessionFactory));
    //设置当前holder和当前事务同步  holder.setSynchronizedWithTransaction(
    true);
    //holder 引用次数+1 holder.requested(); }
    else { if (TransactionSynchronizationManager.getResource(environment.getDataSource()) == null) { if (LOGGER.isDebugEnabled()) { 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 { if (LOGGER.isDebugEnabled()) { LOGGER.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active"); } } }

    4. 在sqlSession 关闭session 的时候, 使用了工具了sqlSessionUtils的closeSqlSession 方法。sqlSessionHolder  也是做了判断,如果回话在事务当中,则减少引用次数,没有真实关闭session。如果回话不存在事务,则直接关闭session

      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);
    //如果holder 中持有sqlSession 的引用,(即会话存在事务)
    if ((holder != null) && (holder.getSqlSession() == session)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Releasing transactional SqlSession [" + session + "]"); }
        //每当一个sqlSession 执行完毕,则减少holder 持有引用的次数 holder.released(); }
    else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Closing non transactional SqlSession [" + session + "]"); }
    //如果回话中,不存在事务,则直接关闭session session.close(); } }
  • 相关阅读:
    vue 解析二维码
    自定义组件双向数据绑定,父v-model,子value用.$emit('input', newVal)
    懒加载组件
    float双飞布局
    [转]MySQL 8.0 Public Key Retrieval is not allowed 错误的解决方法
    【转】nginx产生【413 request entity too large】错误的原因与解决方法
    [其它]三维立体图简单入门含样例
    [其它] 美图看看 黑色皮肤下载不了
    vue element 表格内容文字太长加提示
    gitee webide怎么暂存文件(吐槽,gitee的产品真是吃屎的)
  • 原文地址:https://www.cnblogs.com/chihirotan/p/6592759.html
Copyright © 2011-2022 走看看