catalogue
3, Integration implementation ① (SqlSessionTemplate)
4, Integration implementation ② (SqlSessionDaoSupport)
Container management transactions
Programming transaction management
1, Introduction
1. What is mybatis spring?
MyBatis Spring will help you seamlessly integrate MyBatis code into Spring. It will allow MyBatis to participate in Spring's transaction management, creating mappers and mappers SqlSession And inject it into the bean, and convert the exception of MyBatis into the exception of Spring DataAccessException. Finally, you can make the application code independent of MyBatis, Spring or MyBatis Spring.
2. Knowledge base
Before you start using MyBatis Spring, you need to be familiar with the two frameworks Spring and MyBatis and their terms.
Mybatis spring requires the following versions:
MyBatis-Spring | MyBatis | Spring framework | Spring Batch | Java |
---|---|---|---|---|
2.0 | 3.5+ | 5.0+ | 4.0+ | Java 8+ |
1.3 | 3.4+ | 3.2.2+ | 2.1+ | Java 6+ |
2, Quick start
Import dependencies in pom.xml:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency>
To use MyBatis with Spring, you need to define at least two things in the Spring application context: one SqlSessionFactory And at least one data mapper class.
In mybatis Spring, you can use SqlSessionFactoryBean SqlSessionFactory. You only need to put the following code in the XML configuration file of Spring, where you need a datasource:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean>
Suppose a mapper interface is defined as follows:
public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{userId}") User getUser(@Param("userId") String userId); }
You can add interfaces to Spring through MapperFactoryBean:
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
Note: the specified mapper class must be an interface rather than a specific implementation class. The above example uses annotations or xml configuration.
After configuration, you can directly inject the mapper into the service object like the ordinary bean injection method in Spring. MapperFactoryBean handles the creation and closing of SqlSession. If Spring transactions are used, the session will commit or roll back when the transaction is completed. Finally, any exception will be translated into Spring's DataAccessException exception.
Finally, calling the Mybatis data method requires only one line of code.
public class UserServiceImpl implements UserService { private UserMapper userMapper; public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } public User findUserById(String userId) { return this.userMapper.getUser(userId); }
MapperFactoryBean: this class allows you to directly inject the data mapper interface into your service layer bean. When using mappers, just call them like your DAO.
3, Integration implementation ① (SqlSessionTemplate)
SqlSessionTemplate is the core of mybatis spring.
It is responsible for managing the SqlSession of MyBatis, calling the SQL method of MyBatis, and translating exceptions. SqlSessionTemplate is thread safe and can be shared by multiple Daos. It manages the life cycle of the session, including the necessary shutdown, commit, or rollback operations.
SqlSessionTemplate implements the SqlSession interface. There is no need to replace the SqlSession of MyBatis in the code. SqlSessionTemplate is usually used to replace the DefaultSqlSession of the default MyBatis implementation.
SqlSessionDaoSupport requires an sqlSessionFactory or sqlSessionTemplate property to set.
1. Introduce Spring configuration file beans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
2. Configure the data source to replace the data source of mybaits
<!--Configure data sources: there are many data sources. You can use third-party or Spring of--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean>
3. Configure SqlSessionFactory and associate MyBatis
<!--to configure SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--relation Mybatis--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/jacko/dao/*.xml"/> </bean>
4. Register sqlSessionTemplate and associate sqlSessionFactory
<!--register sqlSessionTemplate , relation sqlSessionFactory--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--Using constructor injection--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
5. Add the implementation class of Dao interface; Privatize sqlSessionTemplate
public class UserDaoImpl implements UserMapper { //sqlSession does not need to be created by ourselves, but managed by Spring private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } public List<User> selectUser() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser(); } }
6. Register bean implementation
<bean id="userDao" class="com.jacko.dao.UserDaoImpl"> <property name="sqlSession" ref="sqlSession"/> </bean>
7. Testing
@Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserMapper mapper = (UserMapper) context.getBean("userDao"); List<User> user = mapper.selectUser(); System.out.println(user); }
The result is output successfully! Now the status of our Mybatis configuration file! Discovery can be integrated by Spring
4, Integration implementation ② (SqlSessionDaoSupport)
SqlSessionDaoSupport is an abstract support class. It is used to provide you with SqlSession. Call getSqlSession() method to get a SqlSessionTemplate, which can be used to execute SQL methods.
Mybatis spring version 1.2.3 and above can use this implementation
dao inherits the Support class, obtains it directly by using getSqlSession(), and then injects it directly into SqlSessionFactory. Compared with the first method, this method does not need to manage SqlSessionTemplate, and the Support for transactions is more friendly
1. Modify the UserDaoImpl we wrote above
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper { public List<User> selectUser() { UserMapper mapper = getSqlSession().getMapper(UserMapper.class); return mapper.selectUser(); } }
2. Modify bean configuration
<bean id="userDao" class="com.kuang.dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
3. Testing
@Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserMapper mapper = (UserMapper) context.getBean("userDao"); List<User> user = mapper.selectUser(); System.out.println(user); }
5, Business
One of the main reasons for using MyBatis Spring is that it allows MyBatis to participate in Spring's transaction management. MyBatis Spring leverages the data source transaction manager that exists in Spring.
After configuring Spring's transaction manager, you can configure transactions in Spring. It also supports @ Transactional annotation and AOP style configuration. A separate SqlSession object will be created and used during the transaction. When the transaction is completed, the session will be committed or rolled back in an appropriate manner.
First, open the Spring transaction processing function and create a DataSourceTransactionManager object.
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
Note: the DataSource specified for the transaction manager must be the same data source used to create the SqlSessionFactoryBean, otherwise the transaction manager will not work.
Container management transactions
If you want Spring to participate in container managed transactions (CMT), Spring should be configured using JTA transaction manager or its container specified subclasses
<tx:jta-transaction-manager />
If you want to use CMT instead of Spring's transaction management. SQLSessionFactory must be configured to use MyBatis's ManagedTransactionFactory
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="transactionFactory"> <bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" /> </property> </bean>
Programming transaction management
MyBatis SqlSession Provides several ways to handle transactions in code. However, you cannot call SqlSession.commit(), SqlSession.rollback(), on a Spring managed sqlsession or SqlSession.close() method. If this is done, it will be thrown UnsupportedOperationException Abnormal.
If you want to programmatically control transactions, this code shows how to use platform transaction manager to process transactions
DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); try { userMapper.insertUser(user); } catch (MyException ex) { txManager.rollback(status); throw ex; } txManager.commit(status);
6, Using SQLSession
In MyBatis, you can use SqlSessionFactory to create sqlsessions. Once you get a session, you can use it to execute mapping statements, commit or roll back connections. Finally, you can close the session when it is no longer needed. After using MyBatis Spring, you no longer need to use SqlSessionFactory directly, because your bean can be injected through a thread safe SqlSession, and automatically commit, rollback and close the session based on the transaction configuration of Spring.