一、前言

MyBatis-Plus 是一个 Mybatis 增强版工具,在 MyBatis 上扩充了其他功能没有改变其基本功能,为了简化开发提交效率而存在。

二、整合MybatisPlus

新建一个Spring Boot项目,

2.1 引入依赖

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
        <dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>

2.2 application.yml

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
spring:
datasource:
druid:
# 数据库访问配置, 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowMultiQueries=true&useSSL=false
username: spring
password: spring#123
# 连接池配置
initial-size: 5
min-idle: 5
max-active: 20
# 连接等待超时时间
max-wait: 30000
# 配置检测可以关闭的空闲连接间隔时间
time-between-eviction-runs-millis: 60000
# 配置连接在池中的最小生存时间
min-evictable-idle-time-millis: 300000
validation-query: select '1' from dual
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打开PSCache,并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-open-prepared-statements: 20
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙
filters: stat,wall
# Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
aop-patterns: com.wno704.boot.servie.*

# WebStatFilter配置
web-stat-filter:
enabled: true
# 添加过滤规则
url-pattern: /*
# 忽略过滤的格式
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'

# StatViewServlet配置
stat-view-servlet:
enabled: true
# 访问路径为/druid时,跳转到StatViewServlet
url-pattern: /druid/*
# 是否能够重置数据
reset-enable: false
# 需要账号密码才能访问控制台
login-username: druid
login-password: druid123
# IP白名单
# allow: 127.0.0.1
# IP黑名单(共同存在时,deny优先于allow)
# deny: 192.168.1.218

# 配置StatFilter
filter:
stat:
log-slow-sql: true

mybatis-plus:
configuration:
map-underscore-to-camel-case: true
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:mapper/*Mapper.xml
global-config:
# 逻辑删除配置
db-config:
# 删除前
logic-not-delete-value: 1
# 删除后
logic-delete-value: 0

2.3 分页插件配置

创建MybatisPlusConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
@MapperScan("com.wno704.boot.mapper")
public class MybatisPlusConfig {

/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}

@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}

2.4 自动生成代码

创建GeneratorCodeConfig.java

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
public class GeneratorCodeConfig {

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.isNotEmpty(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");
projectPath = "E:\\workspace\\workspace(idea)\\spring\\boot\\24springboot-mybatisplus";
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("wno704");
gc.setOpen(false);
//实体属性 Swagger2 注解
gc.setSwagger2(false);
mpg.setGlobalConfig(gc);

// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowPublicKeyRetrieval=true&allowMultiQueries=true&useSSL=false");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("spring");
dsc.setPassword("spring#123");
mpg.setDataSource(dsc);

// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent("com.wno704.boot");
pc.setEntity("model");//entity
pc.setMapper("mapper");
pc.setService("service");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);


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

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

// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);

strategy.setEntityLombokModel(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}

}

2.5 数据准备

这里我们使用以前的测试数据,这里以sys_log表做测试

2.6 测试

运行GeneratorCodeConfig.java,输入sys_log

生产代码如下:

我们编写控制代码调用

1
2
3
4
5
6
7
    @Autowired
private ISysLogService iSysLogService;

@RequestMapping( value = "/getLog", method = RequestMethod.GET)
public SysLog getLog(){
return iSysLogService.getById(1);
}

启动项目,浏览器访问: http://localhost:8080/sys-log/getLog

三、自定义sql

3.1 定义Mapper.xml

在resources目录下新建mapper文件夹,新建SysLogMapper.xml文件:

1
2
3
4
5
6
7
8
9
10
11
<?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.wno704.boot.mapper.SysLogMapper">

<!-- 查找所有信息 -->
<select id="findAllSysLog" resultType="com.wno704.boot.model.SysLog">
select * from sys_log
</select>

</mapper>

3.2 代码改造

SysLogMapper.java新增findAllSysLog(),代码如下:

1
2
3
4
5
public interface SysLogMapper extends BaseMapper<SysLog> {

public List<SysLog> findAllSysLog();

}

ISysLogService.java新增findAllSysLog(),代码如下:

1
2
3
public interface ISysLogService extends IService<SysLog> {
public List<SysLog> findAllSysLog();
}

SysLogServiceImpl.java新增findAllSysLog(),代码如下:

1
2
3
4
5
6
7
8
9
10
11
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements ISysLogService {

@Autowired
private SysLogMapper sysLogMapper;

@Override
public List<SysLog> findAllSysLog() {
return sysLogMapper.findAllSysLog();
}
}

SysLogController.java新增getAllLog(),代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RestController
@RequestMapping("/sys-log")
public class SysLogController {

@Autowired
private ISysLogService iSysLogService;

@RequestMapping( value = "/getLog", method = RequestMethod.GET)
public SysLog getLog(){
return iSysLogService.getById(1);
}

@RequestMapping( value = "/getAllLog", method = RequestMethod.GET)
public List<SysLog> getAllLog(){
return iSysLogService.findAllSysLog();
}
}

3.3 测试

启动项目,浏览器访问: http://localhost:8080/sys-log/getAllLog

控制台显示如下:

mybatis-plus3.3之前的版本参考 https://www.cnblogs.com/liuyj-top/p/12976396.html

四、分页查询

4.1 代码改造

ISysLogService.java新增findSysLogByPage(),代码如下:

1
    public List<SysLog> findSysLogByPage(Integer currpage, Integer pagesize);

SysLogServiceImpl.java新增findSysLogByPage(),代码如下:

1
2
3
4
5
6
7
8
9
    @Override
public List<SysLog> findSysLogByPage(Integer currpage, Integer pagesize) {
//分页查询需要配置分页插件
Page<SysLog> page = new Page<>(currpage,pagesize);
IPage<SysLog> pages = sysLogMapper.selectPage(page, null);
System.out.println("总记录数:"+pages.getTotal());
System.out.println("总页数"+pages.getSize());
return pages.getRecords();
}

SysLogController.java新增getLogbyPage(),代码如下:

1
2
3
4
    @GetMapping("getLogbyPage/{currpage}/{pagesize}")
public List<SysLog> getLogbyPage(@PathVariable Integer currpage, @PathVariable Integer pagesize) {
return iSysLogService.findSysLogByPage(currpage,pagesize);
}

4.2 测试

启动项目,使用http请求测试如下:

五、模糊查询

5.1 代码改造

ISysLogService.java新增findSysLogWithMethod(),代码如下:

1
    public List<SysLog> findSysLogWithMethod(String method);

SysLogServiceImpl.java新增findSysLogWithMethod(),代码如下:

1
2
3
4
5
6
7
    @Override
public List<SysLog> findSysLogWithMethod(String method) {
QueryWrapper<SysLog> wrapper = new QueryWrapper<>();
wrapper.like("method",method);
wrapper.orderByDesc(true,"create_time");
return sysLogMapper.selectList(wrapper);
}

SysLogController.java新增getLogbyMethod(),代码如下:

1
2
3
4
    @GetMapping("getLogbyMethod/{method}")
public List<SysLog> getLogbyMethod(@PathVariable String method) {
return iSysLogService.findSysLogWithMethod(method);
}

5.2 测试

启动项目,使用http请求测试如下:

更多条件构造器官方文档