Spring boot enhancement (3) -- Integration and principle analysis of mybatis framework

He Bai Shao er 2020-11-09 22:19:34
spring boot enhancement integration principle


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 :
image.png
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
image.png
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 .

image.png

@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);//conn=HikariProxyConnection@604990529 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

image.png

Business sequence diagram analysis

image.png

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 :

image.png

Business sequence diagram analysis

Product search and log , Its running time sequence analysis , As shown in the figure :

image.png

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);});
}
}
版权声明
本文为[He Bai Shao er]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云