Search code examples
mybatisspring-mybatis

What the SqlSessionHolder is used to do in Mybatis?


In SqlSessionTemplate,getSqlSession and closeSqlSession method all are operate SqlSessionHolder,but i think is not must to do this,Spring manager the transaction and provide ConnectionHolder,transaction is linked about connection.

SqlSessionHolder holder = (SqlSessionHolder) getResource(sessionFactory);

if (holder != null && holder.isSynchronizedWithTransaction()) {
   if (holder.getExecutorType() != executorType) {
       throw new TransientDataAccessResourceException("Cannot change the ExecutorType when there is an existing transaction");
   }

   holder.requested();

   if (logger.isDebugEnabled()) {
      logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
   }

   return holder.getSqlSession();
}

if (logger.isDebugEnabled()) {
  logger.debug("Creating a new SqlSession");
}

SqlSession session = sessionFactory.openSession(executorType);

why we need SqlSessionHolder?


Solution

  • Some session implementations are not stateless in mybatis for performance reasons, they contains local cache.

    So while theoretically it is possible to implement session as a thin wrapper around connection and create new session instance (what would get a connection that is bound to current transaction from spring) every time it is needed that would have a performance penalty in scenarios where cache hits are observed.