summary
Mybatis Is an excellent persistence layer framework , Bottom based JDBC Realize the interaction with database . And in JDBC On the basis of operation, it has done encapsulation and optimization , It relies on Flexible SQL customized , How to map parameters and result sets , Better adapt to the current development of Internet technology .Mybatis The simple application architecture of the framework is shown in the figure :
In today's Internet applications, projects ,mybatis Frames are usually made of spring Framework for resource integration , As a data layer technology to achieve data interaction .
preparation
First step : Create project module
The second step : Add dependency
<dependencies>
<!--spring jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!--mysql drive -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency> <dependency> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions> <exclusion> <groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion> </exclusions> </dependency></dependencies>
The third step :application.properties Add simple configuration to the configuration file
#spring datasource
spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=1234
#spring mybatis
mybatis.mapper-locations=classpath:/mapper/*/*.xml
#spring logs
logging.file.path=D:/logs/
logging.level.com.cy=debug
test Mybatis The underlying environment
stay SpringBoot In scaffold Engineering ,Spring The framework will be based on MyBatis The underlying configuration of the framework , establish SqlSessionFactory object , And then create it through this factory object SqlSession, Based on the Springku The framework injects SqlSession object , Next , We can go through SqlSession The object implements the conversation with the database .
@SpringBootTest
public class MyBatisTests {
/**
* SqlSession This object is mybatis In the framework, we can talk to the database
*/
@Autowired
private SqlSession sqlSession;
@Test
void testGetConnection(){
Connection conn=sqlSession.getConnection();// Where to get the connection from ?
System.out.println("conn="+conn);//[email protected] wrapping com.zaxxer.hikari.pool.ProxyConnection.ClosedConnection
Assertions.assertNotNull(conn);// Assertion testing : Enterprises often use ,
// Judge whether the object is empty , Not empty test passed , Otherwise, throw it out of order
}
}
MyBatis Business code implementation and principle analysis
Business description
be based on SpringBoot Scaffolding works for MyBatis Integration of the framework , Realize the query business of commodity data in commodity database .
API Architecture design
Business sequence diagram analysis
Business code design and Implementation
POJO Entity class
package com.cy.pj.goods.pojo;
import java.util.Date;
/** Used to store product information pojo object */
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;
}
}
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 , The implementation class based on this object operates the data in the commodity library
* @Mapper Mybatis The framework defines , Used to describe the persistence layer , tell mybatis
* This interface implementation class is implemented by mybatis establish , And give it to spring Framework 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>
Define unit test classes , Yes GoodsDao Method for unit testing
package com.cy.pj.goods.dao;
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 GoodsDaoTests {
@Autowired
private GoodsDao goodsDao;// The implementation class is created at the bottom of the runtime , So now we can't find , You can set it up inspections Middle search autowired To change the prompt mode
@Test
void testFindGoods(){
List<Goods> list = goodsDao.findGoods();
for(Goods g:list){
System.out.println(g);
}
}
}
Analyze the principle
Definition GoodsDaoImpl namely GoodsDao Implementation class of interface
package com.cy.pj.goods.dao;
import com.cy.pj.goods.pojo.Goods;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository// Belong to Dao Layer instantiation annotation , hand spring Container management , And tell the container that the object works with the persistence layer , Operate on the database
public class GoodsDaoImpl implements GoodsDao{
public GoodsDaoImpl(){
System.out.println("GoodsDaoImpl()..");
}
@Autowired
private SqlSessionFactory sqlSessionFactory;// Inject defaultSqlSessionFactory object
@Override
public List<Goods> findGoods() {
//1. obtain SqlSession Object call openSession() Method
SqlSession sqlSession = sqlSessionFactory.openSession();
//2. be based on SqlSession Realize commodity query
String statment="com.cy.pj.goods.dao.GoodsDao.findGoods";//namespace+elementId
List<Goods> list = sqlSession.selectList(statment);
//3. Release resources
sqlSession.close();
//4. Return results
return list;
}
}
Then use the test class to test
package com.cy.pj.goods.dao;
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 GoodsDaoTests {
@Autowired
private GoodsDao goodsDao;// The implementation class is created at the bottom of the runtime , So now we can't find , You can set it up inspections Middle search autowired To change the prompt mode
@Test
void testFindGoods(){
List<Goods> list = goodsDao.findGoods();
for(Goods g:list){
System.out.println(g);
}
}
}
One way is to use Xml By mapping sql Statement to execute a query to the database , The other is to make use of SqlSessionFactory Connection in , perform SqlSession Of selectList() Method
Business level records MyBatis Bottom SQL The length of the conversation
Business description
Now there's a business , The data persistence layer needs to be recorded api The execution time when the method is called , How to achieve ?
requirement :
1) We can't write logging directly to unit test classes .
2) We can't modify the data persistence layer implementation class .
API Architecture design
Based on logging business API Design , As shown in the figure :
Business sequence diagram analysis
Product search and log , Its running time sequence analysis , As shown in the figure :
Definition GoodsService Interface
package com.cy.pj.goods.service;
import com.cy.pj.goods.pojo.Goods;
import java.util.List;
public interface GoodsService {
List<Goods> findGoods();
}
Definition GoodsServiceImpl Implement the class and log it
@Service
public class GoodsServiceImpl implements GoodsService{
private static final Logger log=
LoggerFactory.getLogger(GoodsServiceImpl.class);// Parameters are objects of a class , Because the generated log belongs to this class
@Autowired
private GoodsDao goodsDao;
@Override
public List<Goods> findGoods() {
long t1=System.currentTimeMillis();
List<Goods> list = goodsDao.findGoods();
long t2=System.currentTimeMillis();
System.out.println(log.getClass().getName());//ch.qos.logback.classic.Logger Explain that the facade specification is logback
log.info("findGoods()-->t2-t1={}",t2-t1);// Place holder {}, Inside is t2-t1 Result
//System.out.println("t2-t1="+(t2-t1));
return list;
}
}
Write unit test classes GoodsServiceTests, Yes GoodsService Object method for unit testing
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 findGoods(){
List<Goods> list =goodsService.findGoods();
//for(Goods g:list){ System.out.println(g); }
// Change to Lambda Expression to traverse
list.forEach((g)->{System.out.println(g);});
}
}