Integration implementation and principle analysis of mybatis framework in 05 springboot project

Time:2021-4-17

Preliminary analysis of integrating mybatis

summary

Mybatis is an excellent persistence layer framework. The bottom layer is based on JDBC to realize the interaction with database. It is packaged and optimized on the basis of JDBC operation. With the help of flexible SQL customization and mapping of parameters and result sets, it can better adapt to the development of current Internet technology. The simple application architecture of mybatis framework is shown in the figure
Integration implementation and principle analysis of mybatis framework in 05 springboot project
In today’s Internet applications, mybatis framework usually integrates resources by spring framework, as a data layer technology to achieve data interaction.

preparation

Step 1: create a project module, for example:

Integration implementation and principle analysis of mybatis framework in 05 springboot project

Step 2: add dependency

MySQL driven dependency

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

Spring JDBC dependency

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

Mybatis starter dependency

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

Step 2: application.properties Add simple configuration to 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

Implementation of environment test code

Add test classes in Src / test / Java directory to test mybatis framework integration

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 scaffold project, spring framework will create a sqlsessionfactory object based on the underlying configuration of mybatis framework, then create a sqlsession through this factory object, and finally inject a sqlsession object into the test class based on the springku framework. Next, we can realize the session with the database through the sqlsession object.

Integration implementation and principle analysis of mybatis framework in 05 springboot project

Implementation and principle analysis of mybatis business code integration

Business description

Based on the integration of mybatis framework in springboot scaffold project, the query business of commodity data in commodity library is realized.

API architecture design

Integration implementation and principle analysis of mybatis framework in 05 springboot project

Business sequence diagram analysis

Integration implementation and principle analysis of mybatis framework in 05 springboot project

Design and implementation of business code

Step 1: define the POJO object type of commodity module (store commodity data based on this object). The code is as follows:

package com.cy.pj.goods.pojo;
import java.util.Date;
/**POJO object for storing commodity 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 commodity module persistence layer object. 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 this object's implementation class operation commodity library data
 *It is defined in the @ mapper mybatis framework to describe the persistence layer interface and tell mybatis
 *The implementation class of this interface is created by mybatis and managed by spring framework
 * */
@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 of test code

Define the unit test class and 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);
        }
    }
}

Test run, bottom API analysis, as shown in the figure:

Integration implementation and principle analysis of mybatis framework in 05 springboot project

Bug analysis during test run

  • The @ Autowired annotation error prompt configuration in idea is shown as follows:

Integration implementation and principle analysis of mybatis framework in 05 springboot project

  • Bindingexception, as shown in the figure:

Integration implementation and principle analysis of mybatis framework in 05 springboot project

  • Unit test class location error, as shown in the figure:

Integration implementation and principle analysis of mybatis framework in 05 springboot project

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

Integration implementation and principle analysis of mybatis framework in 05 springboot project

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 API method call of data persistence layer. How to implement it?
requirement:
1) We can’t write the log directly to the unit test class.
2) We cannot modify the data persistence layer implementation class.

API architecture design

The API is designed based on the logging service, as shown in the figure

Integration implementation and principle analysis of mybatis framework in 05 springboot project

Business sequence diagram analysis

The running time sequence analysis is shown in the figure

Integration implementation and principle analysis of mybatis framework in 05 springboot project

Design and implementation of business code

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:

Integration implementation and principle analysis of mybatis framework in 05 springboot project

Writing and running of test code

Write the unit test class goodsservicetests to unit test the goodsservice object method, 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 run

  • NullPointerException, as shown in the figure:

Integration implementation and principle analysis of mybatis framework in 05 springboot project

  • Nosuchbeandefinitionexception, as shown in the figure:

Integration implementation and principle analysis of mybatis framework in 05 springboot project

Summary

This section is a basic introduction of mybatis framework, and based on the springboot project to do the integration of mybatis framework, focusing on its application architecture, code structure, writing process, running process, problem analysis and corresponding solutions in the implementation process.