Preliminary analysis of integrated MyBatis
An overview of the
Mybatis is an excellent persistence layer framework, which implements the interaction with database based on JDBC. And in the JDBC operation on the basis of encapsulation and optimization, it with the help of flexible SQL customization, parameters and result set mapping, better adapt to the development of the current Internet technology. The simple application architecture of Mybatis framework is shown in the figure below:
In today’s Internet application projects, Mybatis framework usually integrates resources by Spring framework and realizes data interactive operation as data layer technology.
The preparatory work
Step 1: Create the project Module, for example:
Step 2: Add dependencies
Mysql driver dependencies
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
Copy the code
Spring JDBC rely on
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
Copy the code
Mybatis starter rely on
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> The < version > 2.1.1 < / version > < / dependency >Copy the code
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=rootCopy the code
Mybatis configuration
mybatis.mapper-locations=classpath:/mapper/*/*.xml
Copy the code
Environment test code implementation
Add the test class to the SRC /test/ Java directory to conduct the basic test of 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); }}Copy the code
SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory Finally, based on Springku framework for test class injection SqlSession object, next, we can use SqlSession object to achieve the session with the database.
Integrated MyBatis business code implementation and principle analysis
Business description
Based on the integration of MyBatis framework by SpringBoot scaffolding engineering, the query business of commodity data in commodity database is realized.
API Architecture Design
Business sequence diagram analysis
Business code design and implementation
Step 1: Define the commodity module POJO object type (on which to store the commodity data) as follows:
package com.cy.pj.goods.pojo; import java.util.Date; /** 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; }}Copy the code
Step 2: Define the GoodsDao interface and method mapping of the persistence layer object of the commodity module
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; /** The implementation class of this interface is created by MyBatis and given to the Spring framework to manage. ** / @Mapper public interface GoodsDao { List<Goods> findGoods(); }Copy the code
GoodsDao interface mapping file and SQL mapping definition
<? The 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>Copy the code
Test code writing and running
Define unit test classes to unit test GoodsDao methods, 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); }}}Copy the code
Test run, underlying API analysis, as shown in the figure:
BUG analysis during test run
- The @autowired annotation in IDEA indicates an error configuration, as shown in the figure below:
- BindingException, as shown:
- Unit test class location error, as shown in figure:
- The corresponding mapping element cannot be found, as shown in the figure:
The business layer records the underlying SQL session duration of MyBatis
Business description
There is a business that needs to record the execution time of data persistence layer API method calls. How to implement this?
Requirements:
1) We cannot write logging 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:
Business sequence diagram analysis
Commodity query and log recording, and its running time sequence analysis, as shown in the figure:
Business code design and implementation
Step 1: Define the GoodsService interface 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();
}
Copy the code
Step 2: Define and log the GoodsServiceImpl implementation class 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); // Return list; }}Copy the code
Log API application analysis, as shown in the figure:
Test code writing and running
Write the unit test class GoodsServiceTests to unit test GoodsService object methods, 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); }}}Copy the code
BUG analysis during test run
- NullPointerException, as shown:
- NoSuchBeanDefinitionException, as shown:
Summary (Summary)
This section is mainly a basic introduction of MyBatis framework, and based on the Springboot project to do the integration of MyBatis framework, focusing on mastering its application architecture, code structure, writing process, running process and in the process of implementation of the problem analysis and corresponding solutions.
Source: www.tuicool.com/articles/bI…