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

Time:2020-11-28

Preliminary analysis of integrating mybatis

summary

Mybatis is is an excellent persistence layer framework. The underlying layer is based on JDBC to realize the interaction with database. And on the basis of JDBC operation, it is packaged and optimized. 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
Integrated implementation and principle analysis of mybatis framework in 05 springboot project
In today’s Internet applications, mybatis framework is usually integrated by spring framework as a data layer technology to achieve data interaction.

preparation

Step 1: create the project module, for example:
Integrated implementation and principle analysis of mybatis framework in 05 springboot project
Step 2: add dependencies
MySQL driver 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

Environment test code implementation

Add a test class to the Src / test / Java directory to test the mybatis framework integration. 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 scaffold project, the spring framework will create a sqlsessionfactory object based on the underlying configuration of mybatis framework, and then create a sqlsession through this factory object. Finally, the sqlsession object is injected into the test class based on the springku framework. Next, we can realize the session with the database through the sqlsession object.
Integrated implementation and principle analysis of mybatis framework in 05 springboot project

Implementation and principle analysis of integrated mybatis business code

Business description

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

API architecture design

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

Business sequence diagram analysis

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

Business code design and Implementation

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

package com.cy.pj.goods.pojo;
import java.util.Date;
/**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 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 the implementation class of this object to operate the data in the commodity library
 *It is defined in mapper mybatis framework, which is used to describe the persistence layer interface and tell mybatis
 *The implementation class of this interface is created by mybatis and managed by the 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 to 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, analysis of underlying API, as shown in the figure:
Integrated implementation and principle analysis of mybatis framework in 05 springboot project

Bug analysis in test running process

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

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

  • Bindingexception, as shown in the figure:

Integrated implementation and principle analysis of mybatis framework in 05 springboot project
Solution: mainly look at the configuration in the mapping file XML.

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

Integrated implementation and principle analysis of mybatis framework in 05 springboot project
Solution: check whether the test class is in the test package or sub package.

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

Integrated implementation and principle analysis of mybatis framework in 05 springboot project
Solution: if you access the database through the method of sqlseaaion object, you should write according to the standard of statement.

The business layer records the duration of mybatis underlying SQL session

Business description

Now there is a business that needs to record the execution time of data persistence layer API method call. How to implement it?
requirement:
1) We can’t write log records directly to the unit test class.
2) We cannot modify the data persistence layer implementation class.

API architecture design

API design based on logging service, as shown in the figure:
Integrated implementation and principle analysis of mybatis framework in 05 springboot project

Business sequence diagram analysis

The running time sequence analysis of commodity query and log record is shown in the figure
Integrated implementation and principle analysis of mybatis framework in 05 springboot project

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:
Integrated implementation and principle analysis of mybatis framework in 05 springboot project
Note: the facade mode is used here, and the specific setting methods are as follows:
Integrated implementation and principle analysis of mybatis framework in 05 springboot project

Test log level

package com.cy.pj.goods.service;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
Public class logtests {// test log level
    private static final Logger log= LoggerFactory.getLogger(LogTests.class);
    @Test
 void testLogTest(){
        log.trace (" log.leve=trace "); // debugging phase
 log.debug (" log.leve=debug "); // debugging phase
 log.info("log.leve=info");
        log.warn("log.leve=warn");
        log.error("log.leve=error");
    }
}

The default info in springboot can be configured in the configuration file of springboot
Related issues:

  • 1) What API is used for logging in the project? Slf4j (simple logging facade for Java)
  • 2) Why use this API? (this set of APIs defines the specification of log – coupling specification recommended in the program – its purpose is to improve its scalability)
  • 3) The specific implementation of this set of API, who are you using in the project( ch.qos.logback . classic.Logger )
  • 4) Why don’t you use log4j? (in asynchronous case, logback performs better than log4j, which is built into springboot)
  • 5) Are the logs in your project written synchronously or asynchronously? (mostly asynchronous, improving the user experience)
  • 6) Do you know the level of the log

Writing and running of test code

Write the unit test class goodsservicetests, and carry out unit test on goodsservice object methods, such as:

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 in test running process

  • NullPointerException, null pointer exception, as shown in the figure:

Integrated implementation and principle analysis of mybatis framework in 05 springboot project
Solution: check whether the assignment and management are given to the spring framework, such as whether there are @ Autowired annotation on the attribute and the class of attribute to the spring framework management.

  • Nosuchbeandefinitionexception, the corresponding bean configuration information is not found, as shown in the figure:

Integrated implementation and principle analysis of mybatis framework in 05 springboot project
Solution: whether there is a corresponding implementation class for the interface, and whether the implementation class is managed by the spring framework, such as @ service annotation.

Summary

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