SpringBoot24x整合Mybatis-Plus3

Mybatis和MybatisPlus的区别与联系

Mybatis-Plus是一个Mybatis的增强工具,只是在Mybatis的基础上做了增强却不做改变,MyBatis-Plus支持所有Mybatis原生的特性,所以引入Mybatis-Plus不会对现有的Mybatis构架产生任何影。Mybatis-Plus又简称(MP)是为简化开发,提高开发效率而生正如官网所说的,

image.png
点击这里进入学官网学习

快速与SpringBoot整合基础入门

导入必须依赖

  1. MybatisPlus整合SpringBoot的场景启动器jar
1
2
3
4
5
xml复制代码 <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
  1. 连接mysql的驱动jar
1
2
3
4
5
xml复制代码<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

注意这里没有指定mysql-connector-javajar包版本时SpringBoot会默认为我们指定一个版本

配置数据源

1
2
3
4
5
6
7
8
9
xml复制代码#---------------数据库连接配置--------------
# 用户名
spring.datasource.username=root
# 密码
spring.datasource.password=root
# 连接url
spring.datasource.url=jdbc:mysql://localhost:3306/school?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&autoReconnect=true
# 驱动名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

简单CRUD

编写实体类与数据库映射

实体类Student与数据库表student对应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
JAVA复制代码package cn.soboys.springbootmybatisplus.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;

/**
* @author kenx
* @version 1.0
* @date 2021/6/25 10:08
*/

@TableName("student")
public class Student extends Model {
@TableId(value = "student_id",type = IdType.AUTO)
private Long studentId;
@TableField("student_name")
private String studentName;
@TableField("age")
private int age;
@TableField("phone")
private String phone;
@TableField("addr")
private String addr;


public Long getStudentId() {
return studentId;
}

public void setStudentId(Long studentId) {
this.studentId = studentId;
}

public String getStudentName() {
return studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getAddr() {
return addr;
}

public void setAddr(String addr) {
this.addr = addr;
}
}

编写mapper(dao)与数据库交互

接口StudentMapper具体实现由mybatis代理实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
java复制代码package cn.soboys.springbootmybatisplus.mapper;

import cn.soboys.springbootmybatisplus.bean.Student;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;

/**
* @author kenx
* @version 1.0
* @date 2021/6/25 10:53
*/
@Mapper
public interface StudentMapper extends BaseMapper<Student> {


}

编写service实现具体业务

  1. 接口IStudentService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
java复制代码package cn.soboys.springbootmybatisplus.service;

import cn.soboys.springbootmybatisplus.bean.Student;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.stereotype.Service;

/**
* @author kenx
* @version 1.0
* @date 2021/6/25 10:59
*/

public interface IStudentService extends IService<Student> {
}
  1. 实现类StudentServiceImpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
java复制代码package cn.soboys.springbootmybatisplus.service.impl;

import cn.soboys.springbootmybatisplus.bean.Student;
import cn.soboys.springbootmybatisplus.mapper.StudentMapper;
import cn.soboys.springbootmybatisplus.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
* @author kenx
* @version 1.0
* @date 2021/6/25 13:35
*/
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper,Student> implements IStudentService {
}

编写controller主程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
java复制代码package cn.soboys.springbootmybatisplus.controller;

import cn.soboys.springbootmybatisplus.bean.Student;

import cn.soboys.springbootmybatisplus.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
* @author kenx
* @version 1.0
* @date 2021/6/25 11:09
*/
@RestController
@RequestMapping("/student")
public class StudentController {

@Autowired
private IStudentService studentService;

/**
* 添加学生
*
* @param student
* @return
*/
@PostMapping("/add")
public boolean addStudent(@RequestBody Student student) {
boolean flag = studentService.save(student);
return flag;
}

/**
* 根据id更新学生信息
*
* @param student
* @return
*/
@PutMapping("/update")
public boolean updateStudent(@RequestBody Student student) {
//根据学生id更新学生
boolean flag = studentService.updateById(student);
return flag;
}


/**
* 查找所有学生信息
*
* @return
*/
@GetMapping("/list")
public List<Student> list() {
return studentService.list();
}

/**
* 根据id删除学生信息
*
* @param studentId
* @return
*/
@DeleteMapping("/del/{studentId}")
public boolean del(@PathVariable long studentId) {
boolean flag = studentService.removeById(studentId);
return flag;
}

/**
* 根据id获取学生信息
* @param studentId
* @return
*/
@GetMapping("{studentId}")
public Student getStudentInfo(@PathVariable long studentId){
return studentService.getById(studentId);
}


}

向数据库里添加一个学生

image.png
我们看到返回结果是true 代表添加成功

根据学生id修改刚刚添加学生信息

image.png
我们看到也修改成功返回true,注意这里修改时候多传一个studentId 参数,就是通过学生id找到对应的学生在进行修改。

查询所有的学生信息

image.png

根据学生id删除学生信息

image.png
我们看到返回true代表删除成功

根据id获取某个学生信息

image.png

到这里单张表最基本的crud功能都可以正常使用

SpringBoot整合进阶使用

我们看到上面完成了最基本整合使用很多地方还可以进一步优化

简化实体bean

我们看到上面整合方式Student实体类包含很多getter,setter方法,和一些不非必要的映射注解可以适当的简化

  1. 导入jar包lombok 这里没有写版本默认用springboot给我们指定的一个版本
1
2
3
4
5
java复制代码<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

lombok可以通过注解@Data帮我们自动生成getter,setter 方法我们只需要在对应实体类上添加上这个注解就可以去掉代码中冗余getter,setter 方法。

简化实体bean与数据库映射注解

我们看到上面整合方式Student实体类包含@TableName 注解和很多@TableField注解其实遵守MybatisPlus中java实体类与数据库映射规则可以适当简化默认MybatisPlus会把大驼峰命名法(帕斯卡命名法)转换为数据库对应下划线命名方法

例如实体类名为:OwnUser,会给你对应到数据库中的own_user表
字段StudentId ,会给你对应数据库表中student_id 的字段

所以最终实体类可以简化成如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
java复制代码package cn.soboys.springbootmybatisplus.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;

/**
* @author kenx
* @version 1.0
* @date 2021/6/25 10:08
*/

@TableName
@Data
public class Student extends Model {
@TableId(type = IdType.AUTO)
private Long studentId;
private String studentName;
private int age;
private String phone;
private String addr;
}

简化mapper扫描

上面整合方式会在每个mapper接口类中添加@Mapper注解进行扫描这样会很麻烦造成冗余,我们可以直接在SpringBoot启动类上添加@MapperScan批量扫描mapper 包,当然我们也可以在其他任意配置类上添加@MapperScan批量扫描mapper 包,但一般会在SpringBoot启动类上添加(本质SpringBoot启动类也是配置类),
这样配置比较集中,有意义,也不需要额外去写一个无意的配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
java复制代码package cn.soboys.springbootmybatisplus;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
@MapperScan({"cn.soboys.springbootmybatisplus.mapper"})
public class SpringbootMybatisplusApplication {

private static ApplicationContext applicationContext;

public static void main(String[] args) {
applicationContext = SpringApplication.run(SpringbootMybatisplusApplication.class, args);
//displayAllBeans();
}

/**
* 打印所以装载的bean
*/
public static void displayAllBeans() {
String[] allBeanNames = applicationContext.getBeanDefinitionNames();
for (String beanName : allBeanNames) {
System.out.println(beanName);
}
}
}

这样就可以不用单独在每个mapper接口类添加@Mapper注解进行扫描

数据库连接池配置

上面我们只是进行了简单的数据库连接配置,但是在真正实际应用中都会使用数据库连接池提高数据连接效率,减少不必要数据库资源开销 具体配置如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
xml复制代码#---------------数据库连接配置--------------
#数据源类型
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
# 用户名
spring.datasource.username=root
# 密码
spring.datasource.password=root
# 连接url
spring.datasource.url=jdbc:mysql://localhost:3306/school?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&autoReconnect=true
# 驱动名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#---------------数据库连接池HikariCP配置--------------
#最小空闲连接,默认值10,小于0或大于maximum-pool-size,都会重置为maximum-pool-size
spring.datasource.hikari.minimum-idle=10
#最大连接数,小于等于0会被重置为默认值10;大于零小于1会被重置为minimum-idle的值
spring.datasource.hikari.maximum-pool-size=20
#空闲连接超时时间,默认值600000单位毫秒(10分钟),
# 大于等于max-lifetime且max-lifetime>0,会被重置为0;不等于0且小于10秒,会被重置为10秒。
spring.datasource.hikari.idle-timeout=500000
#连接最大存活时间,不等于0且小于30秒,会被重置为默认值30分钟.设置应该比mysql设置的超时时间短
spring.datasource.hikari.max-lifetime=540000
#连接超时时间:毫秒,小于250毫秒,否则被重置为默认值30秒
spring.datasource.hikari.connection-timeout=60000
#用于测试连接是否可用的查询语句
spring.datasource.hikari.connection-test-query=SELECT 1

MybatisPlus配置

我们看到上面整合只是简单crud,单张表的操作,我们的service,mapper 没有写任何方法只是继承了MybatisPlus 的通用 Mapper,BaseMapper,通用service接口IService以及实现ServiceImpl就具备了基础的crud方法,但是当遇到多表复杂条件查询时候,就需要单独写sql,这时候就需要单独配置了mapper.xml 文件了

1
2
3
4
5
6
7
xml复制代码#--------------------mybatisPlus配置------------------
#mapper.xml 文件位置
mybatis-plus.mapper-locations=classpath:mapper/*.xml
#别名包扫描路径,通过该属性可以给包中的类注册别名
mybatis-plus.type-aliases-package=cn.soboys.springbootmybatisplus.bean
#控制台打印mybatisPlus LOGO
mybatis-plus.global-config.banner=true

MybatisPlus更多详细配置

分页插件使用

在MybatisPlus中也为我们分页做了相关处理我们要做相关配置才能正常使用

SpringBoot配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
java复制代码package cn.soboys.springbootmybatisplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

/**
* @author kenx
* @version 1.0
* @date 2021/6/28 10:19
*/
@SpringBootConfiguration
public class MyBatisCfg {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}

StudentMapper类

1
2
3
4
5
6
7
java复制代码/**
* 分页查询每个班级学生信息
* @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承Page实现自己的分页对象)
* @param gradeId 班级id
* @return 分页对象
*/
IPage<Student> findStudentPage(Page<?> page, long gradeId);

studentMapper.xml

1
2
3
4
xml复制代码<!-- 等同于编写一个普通 list 查询,mybatis-plus 自动替你分页-->
<select id="findStudentPage" resultType="Student">
select * from student ,grade g where g.grade_id=#{gradeId}
</select>

IStudentService 接口

1
2
3
4
5
6
7
java复制代码/**
* 分页查询
* @param page
* @param gradeId 班级id
* @return
*/
IPage<Student> getStudentPage(Page<Student> page,long gradeId);

StudentServiceImpl 实现类

1
2
3
4
5
6
7
8
9
java复制代码@Override
public IPage<Student> getStudentPage(Page<Student> page,long gradeId) {
// 不进行 count sql 优化,解决 MP 无法自动优化 SQL 问题,这时候你需要自己查询 count 部分
// page.setOptimizeCountSql(false);
// 当 total 为小于 0 或者设置 setSearchCount(false) 分页插件不会进行 count 查询
// 要点!! 分页返回的对象与传入的对象是同一个

return this.baseMapper.findStudentPage(page,gradeId);
}

StudentController 主程序调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
java复制代码 /**
* 分页获取学生详细信息
*
* @return
*/
@GetMapping("listDetailPage")
public IPage<Student> getStudentDetailPage(PageRequest request) {
Page<Student> page = new Page<>();
//设置每页显示几条
page.setSize(request.getPageSize());
//设置第几页
page.setCurrent(request.getPageNum());
return studentService.getStudentPage(page, 1);
}

这里需要传递分页等相关信息,可以自己封装一个分页查询通用对象PageRequest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
java复制代码package cn.soboys.springbootmybatisplus;

import lombok.Data;

import java.io.Serializable;

/**
* @author kenx
* @version 1.0
* @date 2021/6/28 10:41
* 分页查询
*/
@Data
public class PageRequest implements Serializable {
private static final long serialVersionUID = -4869594085374385813L;

/**
* 当前页面数据量
*/
private int pageSize = 10;

/**
* 当前页码
*/
private int pageNum = 1;

/**
* 排序字段
*/
private String field;

/**
* 排序规则,asc升序,desc降序
*/
private String order;
}

image.png
我们看到正常分页查询每页显示2条第1页

image.png
第2页

代码生成器

我们知道Mybatis可以通过配置生成基础的实体映射bean,简化我们开发时间,不必要写繁琐的映射bean包括一堆属性,MybatisPlus也有自己的代码生成器AutoGenerator,通过简单配置,我们可以快速生成完整的modelservice,mapper,不需要自己去写然后继承通用mapper,service官网原话如下

image.png

添加依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
xml复制代码 <!--生成器依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!--MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:-->
<!--添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、
Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,
如果都不满足您的要求,可以采用自定义模板引擎。-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>

自定义生成器代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
java复制代码package cn.soboys.springbootmybatisplus;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
* @author kenx
* @version 1.0
* @date 2021/6/28 11:31
* 自动代码生成器
*/
public class MyBatisGeneratorCode {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}

public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();

// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("kenx");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);

// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/school?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);

// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("cn.soboys.springbootmybatisplus.generator");
mpg.setPackageInfo(pc);

// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};

// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";

// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/generator/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);

// 配置模板
TemplateConfig templateConfig = new TemplateConfig();

// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();

templateConfig.setXml(null);
mpg.setTemplate(templateConfig);

// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}

运行后的结果

image.png
我们看到运行成功已经正常生成我们需要的目录结构

image.png

image.png
这个模版是通用模版只需要,稍微改一下自己需要生成数据库目录就可以使用了

更多内容参考官网

SpringBoot整合高阶使用

调试打印应sql

在开发中我们常常需要调试代码,需要看看生成sql是否正确,这个时候就需要在控制台打印sql

导入依赖

1
2
3
4
5
6
pom复制代码<!-- https://mvnrepository.com/artifact/p6spy/p6spy -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.0</version>
</dependency>

配置文件配置

1
2
3
4
5
properties复制代码#url 改为p6spy开头的连接url
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/school?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&autoReconnect=true
# 驱动名称
# 需要调试拦截打印sql 驱动改为p6spy 拦截
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver

spy配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
properties复制代码#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

我们看到通过简单配置控制台成功打印出运行sql

image.png

GitHub项目源码

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%