SqlSessionTemplate
SqlSessionTemplate is the core of MyBatis-Spring. This class is responsible for managing MyBatis' SqlSession, calling MyBatis' SQL method, and translating exceptions. SqlSessionTemplate is thread-safe and can be shared and used by multiple DAOs.
When calling SQL methods, it contains the method returned from the mapper getMapper() method. SqlSessionTemplate will ensure that the SqlSession used is related to the current Spring transaction. Additionally, it manages the life cycle of the session, including the necessary closing, commit or rollback operations.
SqlSessionTemplate implements SqlSession, which means that it is necessary to simply replace the SqlSession of MyBatis.
SqlSessionTemplate is usually used to replace the default MyBatis implementation of DefaultSqlSession because it cannot participate in Spring transactions or injected because it is thread-insecure. Transformation between two classes in the same application can cause problems with data consistency.
The SqlSessionTemplate object can be created using SqlSessionFactory as a parameter to construct the method.
<bean id="sqlSession"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
This bean can now be injected directly into the DAO bean. You need to add a SqlSession property to the bean, like the following code:
public class UserDaoImpl implements UserDao{ private SqlSession sqlSession; public void setSqlSession(SqlSession sqlSession){ this.sqlSession = sqlSession; } public User getuser(String userId){ return (User)sqlSession.selectOne ("org.mybatis.spring.sample.mapper.UserMapper.getUser",userId); } }Inject SqlSessionTemplate as follows:
<bean id="userDao"> <property name="sqlSession" ref="sqlSession"/> </bean>
SqlSessionDaoSupport
SqlSessionDaoSupport is an abstract support class used to provide you with SqlSession. Calling the getSqlSession() method you will get a SqlSessionTemplate, which can then be used to execute the SQL method, like this:
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{ public User getUser(String userId){ return (User)getSqlSession().selectOne ("org.mybatis.spring.sample.mapper.UserMapper.getUser",userId); } } Usually MapperFactoryBean is the first choice for this class because it does not require extra code. However, if you need to do other non-MyBatis work in DAO or need specific classes, this class is useful. SqlSessionDaoSupport requires a sqlSessionFactory or sqlSessionTemplate property to set. These are explicitly set up or automatically assembled by Spring. If both are set, then the sqlSessionFactory is ignored.
Assume that the class UserMapperImpl is a subclass of SqlSessionDaoSupport, it can be configured as follows in Spring:
<bean id="userMapper"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>