Get to know Spring | Spring integrates Mybatis

Integrate mybatis

  • mybatis realizes the efficient management of database operations, while spring realizes the creation and use of objects in a new way.

Integrating mybatis is to combine the data manipulation of mybatis with the control inversion of spring.

  1. Import related jar packages

  2. <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>ssm-spring</artifactId>
            <groupId>org.example</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>spring_08</artifactId>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.10.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.6</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    </project>
    

    Transform mybatis

    • Originally, our mybatis has User entity class, UserMapper interface and UserMapper XML, and mybatis config xml.

    The main thing is to transform the mybatis config file. We need to transfer some operations of mybatis connecting to the database to spring for operation together.

    Create a new spring config XML file

    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <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=false&amp;useUnicode=true&amp;characterEncoding=utf8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
    
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:com/lyj/mapper/*.xml"/>
        </bean>
    
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
        
        <bean id="userMapperImpl" class="com.lyj.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
    
    </beans>
    

    In this file, we integrate the acquisition of Sqlsession, the connection to the database and some configurations of mybatis.

  3. Operation sqlsession

    1. In the test class, use getbean() to get the session

      @Test
          public void test_03() {
              ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
              SqlSession sqlSession = (SqlSession) context.getBean("sqlSession");
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
              List<User> allUsers = mapper.findAllUsers();
              for (User u: allUsers) {
                  System.out.println(u);
              }
          }
      
    2. The session is injected through a UserMapperImpl implementation class. (specification)

      public class UserMapperImpl implements UserMapper{
      
          private SqlSessionTemplate sqlSession;
      
          public void setSqlSession(SqlSessionTemplate sqlSession) {
              this.sqlSession = sqlSession;
          }
      
          @Override
          public List<User> findAllUsers() {
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              return userMapper.findAllUsers();
          }
      }
      

      The official document specification is implemented in the second way, which is more in line with the idea of spring dependency injection.

optimization

  1. The configuration part is separated from ordinary bean injection by import

    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <import resource="spring-config.xml"/>
    
        <bean id="userMapperImpl" class="com.lyj.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
    
    </beans>
    
  2. Further simplify the acquisition of sqlsession.

    • mybatis-spring1. Version 2.3 or above can be used

    • Inherit SqlSessionDaoSupport, directly use getSqlSession() to obtain Sqlsession, and directly inject sqlsessionfactory (originally sqlSession) into UserMapperIml in bean management.

    public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
        @Override
        public List<User> findAllUsers() {
            return getSqlSession().getMapper(UserMapper.class).findAllUsers();
        }
    }
    

    Inject sqlSessionFactory.

    <bean id="userMapperImpl2" class="com.lyj.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
    
  3. Separating UserMapperImpl into service layers

    There is a usermapper If you implement a UserMapperImpl after XML, the logic will be a little messy. You can separate the UserMapperImpl and build a service layer separately. Obtain the session at this level.

    1. Inject session type

      public class UserServiceImpl implements UserService{
      
          private SqlSessionTemplate sqlSession;
      
          public void setSqlSession(SqlSessionTemplate sqlSession) {
              this.sqlSession = sqlSession;
          }
      
          @Override
          public List<User> findAllUsers() {
              return sqlSession.getMapper(UserMapper.class).findAllUsers();
          }
          
      }
      
    2. Inherit SqlSessionDaoSupport class

      public class UserServiceImpl2 extends SqlSessionDaoSupport implements UserService{
          
          @Override
          public List<User> findAllUsers() {
              return getSqlSession().getMapper(UserMapper.class).findAllUsers();
          }
      }
      
  4. The method of obtaining sesission is further simplified:

    When we have more operations to obtain sessions, we hope to obtain sessions in a more efficient and manageable way.

    The spring framework provides an operation of automatically scanning mappercannerconfigurer. It can automatically inject our session into all mappers under the package name by setting the properties of this class and automatically scanning the specified package.

    We can directly obtain the mapper to operate, and hand over the acquisition of session to spring encapsulation.

    usage method:

    1. Profile:

      It needs to manually set two properties to inject session for the specified package name

      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
          <property name="basePackage" value="com.lyj.mapper"/>
      </bean>
      
    2. call

      private UserMapper userMapper;
      

      It can be used directly.

Keywords: Java Mybatis Spring

Added by stephenalistoun on Tue, 25 Jan 2022 21:12:38 +0200