Simple relationship among SqlSession, SqlSessionTemplate, SessionFactory and SqlSessionFactoryBean in Mybatis

Posted by stennchau on Tue, 08 Feb 2022 21:16:23 +0100

When learning mabatis or looking at the company's mybatis project, many beginners are always confused about the relationship between SqlSessionSql, SqlSessionTemplate, SessionFactory and SqlSessionFactoryBean. Especially when we look at other people's code, different projects are completed by different people with different styles. Some people use the form of spring configuration, Some people use the form of spring boot hard coding, more complex projects, the use of read-write separation and so on, which is easy to confuse people. The purpose of this article is to clarify the relationship between them in an easy to understand way.

SqlSession and SqlSessionTemplate

First of all, the relationship between SqlSession and SqlSessionTemplate is brought to you. Look at the figure first and then the description.

The following is the source code of SqlSession

package org.apache.ibatis.session;

import java.io.Closeable;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.BatchResult;

public interface SqlSession extends Closeable {


  <T> T selectOne(String statement);


  <T> T selectOne(String statement, Object parameter);


  <E> List<E> selectList(String statement);


  <E> List<E> selectList(String statement, Object parameter);

  <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds);


  <K, V> Map<K, V> selectMap(String statement, String mapKey);

  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey);


  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds);

  <T> Cursor<T> selectCursor(String statement);

  <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds);


  void select(String statement, Object parameter, ResultHandler handler);

  void select(String statement, ResultHandler handler);

  void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler);

  int insert(String statement);


  int insert(String statement, Object parameter);

  int update(String statement);


  int update(String statement, Object parameter);


  int delete(String statement);


  int delete(String statement, Object parameter);


  void commit();


  void commit(boolean force);


  void rollback();


  void rollback(boolean force);


  List<BatchResult> flushStatements();

  @Override
  void close();

  void clearCache();

  Configuration getConfiguration();

  <T> T getMapper(Class<T> type);

  Connection getConnection();
}

The following is the source code of closeable

package java.io;

import java.io.IOException;

public interface Closeable extends AutoCloseable {

    public void close() throws IOException;
}

The following is the source code of autoclosable

package java.lang;

public interface AutoCloseable {
    void close() throws Exception;
}

SqlSession implements the Closeable interface, which means that SqlSession can be closed, that is, SqlSession represents a Closeable connection. Just like his name, session represents a session, which is used to maintain the state information between stateless requests. In the database, SqlSession represents a session between the database client and the database server, and maintains the state information between them.

We can see that SqlSession is an interface, which contains the familiar methods such as select, insert and update for operating the database to execute sql statements. Are you very familiar with them.

The following two are in mybatis-3.4.1 Jar package

The following is in mybatis-spring-1.3.0 Jar package

 

 

SqlSession has three implementation classes. Of course, you can also implement it yourself. DefaultSqlSession is its default implementation class. Of course, there is the familiar SqlSessionTemplate implementation class.

 

 

As you can see, DefaultSqlSession and SqlSessionTemplate are very different

 

In addition to implementing the Sqlsession interface, SqlSessionTemplate also implements the DisposableBean interface, which means that after the instances of SqlSessionTemplate are found by the Bean factory, they will be included in the management process of the whole spring bean life cycle. When the BeanFactory attempts to destroy, the manager of Beans will call the destroy() method of SqlSessionTemplate in a callback manner.

The default implementation is an empty method. You can override it yourself.

To sum up, SqlSessionTemplate is the implementation class of sqlsession. Its name is sqlsession template. With SqlSessionTemplate, we can execute the Sql statements of Dao layer. Having said so much, the key point is that SqlSessionTmplate is the implementation class of sqlsession, and one of the key classes in this implementation class is SqlSessionFactory.

 

 

SqlSessionFactory and SqlSessionFactoryBean

 

SqlSessionFactory is also an interface and a SqlSession factory. Its ability is to open a SqlSession session and overload many different parameters. You can change these parameters to customize some default behaviors during the session. For example, you can set auto commit transactions or turn off auto commit; You can set the type of thread to obtain the database connection (reuse, each new generation, etc.); You can also obtain the Configuration object instance of the Configuration information of the whole Mybatis, and so on.

This is a screenshot of maven

The following is a screenshot of myeclipse

SqlSessionFactory also has two implementation classes by default. Of course, you can also customize the implementation classes. The default implementation is DefaultSqlSessionFactory.

In short, SqlSessionFactory is the factory that produces SqlSession objects. That is to say, in Mybatis, if there is only one database Server to connect, only one factory is needed (only one instance object of SqlSessionFactory), and SqlSession can be closed freely, which means that SqlSession needs to be created repeatedly. As mentioned above, SqlSession is associated with a specific database connection, but if the physical connection is directly operated every time it is created and destroyed, the resource waste is very high and the efficiency is very low. See the method of DefaultSqlSessionFactory:

The above figure is based on the database connection pool, that is to say, when closing the SqlSession instance after a connection is used up, the database connection object is only put back into the object pool without direct destruction. Using the pool technology, the utilization rate of material resources is greatly improved, the connection time is shortened, and the resource utilization is reduced.

At this point, careful friends may have a question about how SqlSessionFactory creates SqlSession, or more specifically, how SqlSessionTemplate, which has to say dynamic proxy. This part is implemented in SqlSessionTemplate and will not be explained for the time being

The next step is SqlSessionFactoryBean

The ApplicationListener interface is implemented. On behalf of SqlSessionFactoryBean, it has the ability to monitor some event notifications sent by the Application.

The FactoryBean interface is implemented. The instance representing SqlSessionFactoryBean is no longer an ordinary bean object, but a factory that can generate its own bean, and the generated bean will be included in the spring life cycle. The bean generated here refers to SqlSessionFactory.

The InitializingBean interface is implemented, which represents that the afterPropertiesSet() method in SqlSessionFactoryBean will be called immediately after the initialization property of the Bean is completed.

As its name suggests, SqlSessionFactoryBean is the factory bean that produces SqlSessionFactory.

in summary

SqlSessionFactoryBean is a factory bean that produces SqlSessionFactory.

SqlSessionFactory is a factory that opens SqlSession sessions. It is an interface that can be implemented according to requirements. Its default implementation class DefaultSqlSessionFactory uses database connection pool technology.

SqlSession is the session information between the client and the database server. There are many methods to operate the database.

SqlSessionTemplate is a concrete implementation of SqlSession.

Topics: Java Mybatis Spring