05-Integrated implementation and principle analysis of MyBatis framework in SpringBoot project

Preliminary Analysis of Integrating MyBatis

Overview

Mybatis is an excellent persistence layer framework, the bottom layer is based on JDBC to realize the interaction with the database. It is encapsulated and optimized on the basis of JDBC operation. With the help of flexible SQL customization, parameter and result set mapping, it better adapts to the development of current Internet technology. The simple application architecture of the Mybatis framework is shown in the figure:

In today's Internet application projects, the mybatis framework is usually integrated by the spring framework to realize data interaction as a data layer technology.

Ready to work

Step 1: Create a project module, for example:

Step 2: Add dependencies

mysql driver dependencies

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>

spring jdbc dependencies

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

mybatis starter dependencies

<dependency>
 <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
 <version>2.1.1</version>
</dependency> 

Step 2: Add a simple configuration to the application.properties configuration file

Connection pool configuration

spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

mybatis configuration

mybatis.mapper-locations=classpath:/mapper/*/*.xml

Environment test code implementation

Add a test class to the src/test/java directory to perform basic tests on the integration of the mybatis framework. The code is as follows:

package com.cy.pj.goods.dao;
import java.sql.Connection;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MyBatisTests {
       @Autowired
       private SqlSession sqlSession;
       @Test
       public void testGetConnection() {
           Connection conn=sqlSession.getConnection();
           System.out.println("connection="+conn);
       }
}

In the SpringBoot scaffolding project, the Spring framework will create a SqlSessionFactory object based on the underlying configuration of the MyBatis framework, then create an SqlSession through this factory object, and finally inject an SqlSession object into the test class based on the Springku framework. Next, we can use the SqlSession object to communicate with the database session.

Integrate MyBatis business code implementation and principle analysis

business description

Based on the integration of the MyBatis framework based on the SpringBoot scaffolding project, the query business of commodity data in the commodity library is realized.

API Architecture Design

Business sequence diagram analysis

Business code design and implementation

Step 1: Define the POJO object type of the commodity module (based on this object to store commodity data), the code is as follows:

package com.cy.pj.goods.pojo;
import java.util.Date;
/**A pojo object for storing product information*/
public class Goods {
    private Long id;
    private String name;
    private String remark;
    private Date createdTime;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Date getCreatedTime() {
        return createdTime;
    }
    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }
}

Step 2: Define the GoodsDao interface and method mapping of the persistence layer object of the commodity module, the code is as follows

GoodsDao interface and method definition

package com.cy.pj.goods.dao;
import com.cy.pj.goods.pojo.Goods;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**Commodity module persistence layer object, based on the implementation class of this object to operate the data in the commodity library
 * @Mapper MyBatis Defined in the framework to describe the persistence layer interface, telling mybatis
 * The implementation class of this interface is created by mybatis and handed over to the spring framework for management.
 * */
@Mapper
public interface GoodsDao {
    List<Goods> findGoods();
}

GoodsDao interface mapping file and SQL mapping definition

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.pj.goods.dao.GoodsDao">
     <select id="findGoods" resultType="com.cy.pj.goods.pojo.Goods">
         select * from tb_goods
     </select>
</mapper>

Writing and running test code

Define a unit test class to unit test the GoodsDao method, for example:

package com.cy.pj.goods.dao;
@SpringBootTest
public class GoodsDaoTests {
    @Autowired
 private GoodsDao goodsDao;
    @Test
 void testFindGoods(){
        List<Goods> list=goodsDao.findGoods();
        for(Goods g:list){
            System.out.println(g);
        }
    }
}

The test runs and the underlying API is analyzed, as shown in the figure:

BUG analysis during test running

  • The @autowired annotation error prompt configuration in idea, as shown in the figure:

  • BindingException, as shown:

  • The unit test class is in the wrong location, as shown:

  • The corresponding mapping element cannot be found, as shown in the figure:

The business layer records the duration of the underlying SQL session of MyBatis

business description

Now there is a business that needs to record the execution time of the data persistence layer api method call. How to achieve it?
Require:
1) We cannot write logging directly into the unit test class.
2) We cannot modify the data persistence layer implementation class.

API Architecture Design

API design based on logging business, as shown in the figure:

Business sequence diagram analysis

Commodity query and log record, its running time sequence analysis, as shown in the figure:

Business code design and implementation

Step 1: Define the GoodsService interface, the code is as follows:

package com.cy.pj.goods.service;
import com.cy.pj.goods.pojo.Goods;
import java.util.List;
public interface GoodsService {
      List<Goods> findGoods();
}

Step 2: Define the GoodsServiceImpl implementation class and log it. The code is as follows:

package com.cy.pj.goods.service;
import com.cy.pj.goods.dao.GoodsDao;
import com.cy.pj.goods.pojo.Goods;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GoodsServiceImpl implements GoodsService{
   private static final Logger log= 
   LoggerFactory.getLogger(GoodsServiceImpl.class);
    @Autowired
 private GoodsDao goodsDao;
    @Override
 public List<Goods> findGoods() {
        long t1=System.currentTimeMillis();
        List<Goods> list=goodsDao.findGoods();
        long t2=System.currentTimeMillis();
        log.info("findGoods()->t2-t1={}",t2-t1);//log output
 return list;
    }
}

Log API application analysis, as shown in the figure:

Writing and running test code

Write the unit test class GoodsServiceTests to unit test the methods of the GoodsService object, for example:

package com.cy.pj.goods.service;
import com.cy.pj.goods.pojo.Goods;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class GoodsServiceTests {
    @Autowired
 private GoodsService goodsService;
    @Test
 void testFindGoods(){
        List<Goods> list=goodsService.findGoods();
        for(Goods g:list){
            System.out.println(g);
        }
    }
}

BUG analysis during test running

  • NullPointerException, as shown:

  • NoSuchBeanDefinitionException, as shown:

Summary

This section mainly provides a basic introduction to the MyBatis framework, and integrates and implements the MyBatis framework based on the springboot project, focusing on mastering its application architecture, code structure, writing process, running process, and problem analysis and corresponding solutions in the implementation process. solution.

Tags: Spring Boot

Posted by gateway69 on Tue, 10 May 2022 19:58:42 +0300