Spring and Mybatis integration

Spring and MyBatis integration

1. Environment construction

  1. Required jar package
    The Spring framework needs to prepare a total of 10 JAR packages, including: 4 core module jars, jars used by AOP development, JDBC and transaction jars (the Commons logging jars that the core container relies on are already included in the lib package of MyBatis framework, so it is unnecessary to add them here)

    Since Spring 3 has been developed before MyBatis 3 is released, and the Spring team does not want to release the non released version of the code based on MyBatis 3 or wait for a long time, so after Spring 3, there is no support for MyBatis 3. In order to meet the needs of MyBatis users for the Spring framework, the MyBatis community has developed a middleware for integrating the two frameworks -- MyBatis Spring

  2. configuration file

1.db.properties File configuration database
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis

First, the configuration of reading the properties file is defined, then the data source is configured, then the transaction manager is configured and transaction annotation is enabled, finally the MyBatis factory is configured to integrate with Spring. Among them, the MyBatis factory is used to build sqlsessionfactory, which is configured through the org.mybatis.spring.SqlSessionFactoryBean class provided in the MyBatis Spring package. In general, two parameters are required for configuration: one is the data source, and the other is the configuration file path of MyBatis. In this way, Spring's IoC container will parse MyBatis's configuration file when initializing the Bean with id sqlsessionfactory, and save it to Spring's Bean together with the data source

2.applicationContext.xml File configuration Spring Data sources
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    <!-- read db.properties -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- Configure data sources -->
    <bean id="dataSource"
        <property name="driverClassName"
        <property name="url"
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="maxTotal" value="${jdbc.maxTotal}"></property>
        <property name="maxIdle" value="${jdbc.maxIdle}"></property>
        <property name="initialSize" value="${jdbc.initialSize}"></property>

    <!-- Transaction manager depends on data source -->
    <bean id="transactionManager"
        <property name="dataSource" ref="dataSource"></property>
    <!-- Register transaction manager driver -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- Mybaits Factory configuration -->
    <bean id="sqlSessionFactory"
        <!-- Inject data source -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- Specify core profile location -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

Since data source information has been configured in Spring, it is no longer necessary to configure data source information in MyBatis configuration file. Here, you only need to use the < typealiases > and < mappers > elements to configure the file alias and specify the Mapper file location

3.mybaits-config.xml File configuration mybaits Of Mapper mapping
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  

	<!-- Configure aliases -->
	<package name="com.clarence.po"/>
	<!-- To configure Mapper -->


2. Development and integration of traditional DAO

When integrating MyBatis and Spring framework with traditional DAO development method, we need to write DAO interface and implementation class of the interface, inject SqlSessionFactory into DAO implementation class, and then create SqlSession through SqlSessionFactory in method body. To do this, we can use the SqlSessionTemplate class or SqlSessionDaoSupport class provided in the MyBatis Spring package to achieve this function

  • SqlSessionTemplate
    It is the core class of MyBatis Spring, which is responsible for managing the SqlSession of MyBatis and calling the SQL method of MyBatis. When the SQL method is called, SqlSessionTemplate will ensure that the SqlSession used is related to the current Spring transaction. It also manages the lifecycle of SqlSession, including the necessary shutdown, commit, and rollback operations.

  • SqlSessionDaoSupport
    Is an abstract support class. It inherits the DaoSupport class and is mainly used as the base class of DAO. You can get the required SqlSession through the getSqlSession() method of SqlSessionDaoSupport class

  1. Implement persistence layer
1.Persistence class
public class Customer {
    private Integer id;
    private String username;
    private String job;
    private String phone;
2.increase CustomerMapper mapping
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  

<mapper namespace="com.clarence.po.CustomerMapper">
	<select id="findCustomerById" parameterType="Integer"
		select * from t_customer where id=#{id}

3.mybatis-config Add mapping
<mapper resource="com/clarence/po/CustomerMapper.xml"/>
  1. Implementation of DAO layer
1.Defining interfaces
public interface CustomerDao {
    Customer findCustomerById(Integer id);

2.Implementation interface
public class CustomerDaoImpl extends SqlSessionDaoSupport
            CustomerDao {
    public Customer findCustomerById(Integer id) {
        //Note 1   
        return this.getSqlSession().selectOne("com.clarence.po.CustomerMapper.findCustomerById",id);     

3.applicationContext.xml Add to bean´╝îinstantiation CustomerDaoImpl
    <bean id="customerDao" class="com.clarence.dao.impl.CustomerDaoImpl">
        <!-- Inject instance object -->
        //Note 2
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>

Note 1: the CustomerDaoImpl class inherits the SqlSessionDaoSupport class and implements the CustomerDao interface. Among them, SqlSessionDaoSupport class needs a SqlSessionFactory or SqlSessionTemplate object when it is used, so it needs to inject a SqlSessionFactory or SqlSessionTemplate to the subclass object of SqlSessionDaoSupport class through Spring. In this way, you can get the SqlSession object by calling the getSqlSession() method of SqlSessionDaoSupport class in the subclass, and use the methods in the SqlSession object

Note 2: a Bean with id of customerDao is created and SqlSessionFactory object is injected into the instantiated object of the Bean

Test implementation

    public void findCustomerByIdDaoTest() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(

//        CustomerDao customerDao = (CustomerDao) applicationContext
//                .getBean("customerDao");
        //The two methods are the same
        CustomerDao customerDao = applicationContext.getBean(CustomerDao.class);
        Customer customer = customerDao.findCustomerById(1);



3. Development and integration of mapper interface

Using the traditional DAO development method can achieve the required functions, but there will be a lot of duplicate code in the implementation class. In the method, you also need to specify the id of the execution statement in the mapping file, and you can't guarantee the correctness of the id at the time of writing (only the runtime can know it)

3.1 MapperFactoryBean based integration

MapperFactoryBean is a class provided by mybatis Spring team to generate Mapper object according to Mapper interface. The following parameters can be configured when the class is used in Spring configuration file.

  • Mappinterface: used to specify an interface
  • SqlSessionFactory: used to specify SqlSessionFactory
  • SqlSessionTemplate: used to specify SqlSessionTemplate
    If set at the same time as SqlSessionFactory, only SqlSessionTemplate will be enabled
1.CustomerMapper Interface
public interface CustomerMapper {
    Customer findCustomerById(Integer id);

2.CustomerMapper Mapping file
<mapper namespace="com.clarence.mapper.CustomerMapper">
	<select id="findCustomerById" parameterType="Integer"
		select * from t_customer where id=#{id}
3.mybaits-config Introduce
<mapper resource="com/clarence/mapper/CustomerMapper.xml"/>    
4.appliactionContext To configure bean
    <bean id = "customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.clarence.mapper.CustomerMapper"/>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
5.Test class
    public void findCustomerByIdMapperTest() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        CustomerMapper customerMapper = applicationContext

        Customer customer = customerMapper.findCustomerById(1);



Test results:

Although the way of programming with Mapper interface is simple, the following specifications need to be followed when using it

  1. The name of the Mapper interface and the corresponding Mapper.xml mapping file must be the same.
  2. The namespace in Mapper.xml file is the same as the classpath of Mapper interface (that is, the interface file and mapping file need to be in the same package)
  3. The method name in the Mapper interface is the same as the id of each execution statement defined in Mapper.xml
  4. The input parameter type of the method in the Mapper interface should be the same as that of the parameterType of each sql defined in Mapper.xml
  5. The output parameter type of Mapper interface method should be the same as the resultType of each sql defined in Mapper.xml

3.2 MapperScannerConfigurer based integration

The MyBatis spring team provides a form of automatic scanning to configure mappers in MyBatis -- using MapperScannerConfigurer class

MapperScannerConfigurer class can be used in Spring configuration file to configure the following properties·

  • basePackage: Specifies the package path where the mapping interface file is located. Semicolons or commas can be used as separators when multiple packages need to be scanned. When a package path is specified, all files in the package and its subpackages are scanned
  • Annotation class: Specifies the annotation name to scan. Only the class identified by the annotation will be configured as a mapper
  • sqlSessionFactoryBeanName: Specifies the Bean name of SqlSessionFactory defined in Spring
  • sqlSessionTemplateBeanName: Specifies the Bean name of the SqlSessionTemplate defined in Spring. If you define this property, sqlSessionFactoryBeanName will not work
  • markerInterface: Specifies the interface to create the mapper
    <! -- mapper agent development, automatic mapping -- >
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <! -- just configure to package -- >
        <property name="basePackage" value="com.clarence.mapper"/>

MapperScannerConfigurer only needs to specify the package to be scanned through the basePackage attribute when it is used. Spring will automatically generate mapper through the interface in the package (so it does not need to be introduced into mybatis-config.xml, and of course, it does not need to configure bean s in applicationContext). However, there should be corresponding XML file and interface (every operation in mapper.xml file), which are Corresponding to a method with the same name in the interface).

Published 29 original articles, won praise 2, visited 1942
Private letter follow

Tags: Mybatis Spring xml JDBC

Posted on Mon, 24 Feb 2020 04:14:08 -0500 by netpumber