SpringBoot 如何集成 MyBatisPlus - SpringBoot 2.7.2实战基础
SpringBoot 2.7.2 学习系列,本节通过实战内容讲解如何集成 MyBatisPlus
本文在前文的基础上集成 MyBatisPlus,并创建数据库表,实现一个实体简单的 CRUD 接口。 MyBatis Plus 在 MyBatis 做了增强,内置了通用的 Mapper,同时也有代码生成器,简化单表的开发工作。
1 准备数据库
1.1 IDEA 配置数据库
可以在 IDEA 中配置数据库,也可以使用 Navicat、DataGrip 等软件连接数据库。这里简单说说使用 IDEA 连接数据库的步骤。
1)点击右侧上方的 Database,在弹出的 Database面板上,点击左上角加号图标,依次选择 Data Source --> MySQL

2)在弹出的窗口中填写 host、port、User、Password,下载MySQL驱动后,点击 Test Connection,测试连接成功后,点击OK即可。

1.2 创建数据库
执行如下建库语句:
create database `hero_springboot_demo`
default character set utf8mb4 collate utf8mb4_general_ci;
1.3 创建表结构
执行如下建表语句:
create table computer
(
id bigint auto_increment,
size decimal(4, 1) comment '尺寸',
operation varchar(32) comment '操作系统',
year varchar(4) comment '年份',
primary key (id)
) comment '电脑';
1.4 初始化数据
insert into computer(size, operation, year)
values (16, 'MacOS', '2022'),
(14, 'MacOS', '2022'),
(15.6, 'MacOS', '2018'),
(13.3, 'MacOS', '2018'),
(15.6, 'MacOS', '2016'),
(13.3, 'MacOS', '2016'),
(14, 'Windows 10', '2022'),
(13, 'Windows 10', '2020'),
(11, 'Windows 10', '2018'),
(14, 'Windows 8', '2022'),
(13, 'Windows 8', '2020'),
(11, 'Windows 8', '2018');
2 添加依赖
需要添加如下依赖:
- mybatis-plus-boot-starter:Mybatis Plus 与 Spring Boot 整合所需;
- mysql-connector-java: MySQL 驱动;
- lombok:可选,简化 Getter、Setter、构造注入等,简化代码。
在 properties 中定义 mybatis-plus 版本号:
<!-- MyBatis Plus 版本 -->
<mybatis-plus.version>3.5.2</mybatis-plus.version>
添加依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
3 代码生成器
MyBatis Plus 提供了代码生成器。在真实的开发中,通常会独立一个工程来生成相关代码,在这里的demo就直接通过单元测试的方式进行了。
3.1 添加代码生成器依赖
代码生成器的依赖为 mybatis-plus-generator,该依赖内部不含模板引擎,需要手动添加模板引擎的依赖,这里使用 freemarker。由于采用单元测试的方式生成代码,还需添加 junit。这三个 dependecy scope 都采用 test 即可。
<properties>
...
<mybatis-plus-generator.version>3.5.3</mybatis-plus-generator.version>
</properties>
dependecies 中:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus-generator.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
3.2 编写单元测试
在 src/test/java 下新建类:com.yygnb.demo.MyBatisPlusGeneratorTest,使用官方提供的新版方式进行代码生成的编写:
@Test
public void testGenerate() {
String url = "jdbc:mysql://localhost:3306/hero_springboot_demo?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root";
String password = "Mysql.123";
String author = "hero-yyg";
String outputDir = "/Users/hero/temp-code";
String parentPackage = "com.yygnb.demo";
String moduleName = null;
String outputFileXml = "/Users/hero/temp-code/xml";
FastAutoGenerator.create(url, username, password)
.globalConfig(builder -> {
builder.author(author) // 设置作者
.outputDir(outputDir); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent(parentPackage) // 设置父包名
.moduleName(moduleName) // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.xml, outputFileXml)); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.addInclude("computer"); // 设置需要生成的表名
// .addTablePrefix("t_", "c_"); // 设置过滤表前缀
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
注意修改方法开始的变量定义,包括 JDBC url、username、password、生成的代码的输出目录,生成的mapper 的输出目录。修改后执行单元测试,在指定的目录 /Users/hero/temp-code下可以看到生成的 controller、service、entity、mapper、xml。
4 代码编写
4.1 实体类
将生成的实体类 Computer 复制到 com.yygnb.demo.entity中,生成的代码包括很多 Getter/Setter 等,可使用 前面引入的 lombok进行修改:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Computer implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 尺寸
*/
private BigDecimal size;
/**
* 操作系统
*/
private String operation;
/**
* 年份
*/
private String year;
}
4.2 mapper 和 service
- 将生成的 mapper 拷贝到
src/main/java中com.yygnb.demo.mapper.ComputerMapper - 将生成的 service 目录整个拷贝到
com.yygnb.demo中 - 将生成的 xml/ComputerMapper.xml 复制到
src/main/resources/mapper下
4.3 编写controller
编写接口 com.yygnb.demo.controller.ComputerController:
package com.yygnb.demo.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yygnb.demo.entity.Computer;
import com.yygnb.demo.service.IComputerService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RequiredArgsConstructor
@RestController
@RequestMapping("/computer")
public class ComputerController {
private final IComputerService computerService;
@GetMapping("/{id}")
public Computer findById(@PathVariable Long id) {
return this.computerService.getById(id);
}
@GetMapping("/find-page/{page}/{size}")
public Page<Computer> findPage(@PathVariable Integer page, @PathVariable Integer size) {
return this.computerService.page(new Page<>(page, size));
}
@PostMapping()
public Computer save(@RequestBody Computer computer) {
computer.setId(null);
this.computerService.save(computer);
return computer;
}
@PutMapping("/{id}")
public Computer update(@PathVariable Long id, @RequestBody Computer computer) {
computer.setId(id);
this.computerService.updateById(computer);
return computer;
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
this.computerService.removeById(id);
}
}
上面包含了五个接口:
1. 根据id查询(get)
2. 分页查询(get)
3. 新增(post)
4. 根据id修改(put)
5. 根据id删除(delete)
4.4 配置分页拦截器
由于上面使用到分页查询,需要配置 MyBatis Plus 中的 Interceptor。创建类: com.yygnb.demo.config.MyBatisPlusConfig:
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
5 配置 MyBatis Plus
5.1 application.yml
在application.yml 配置数据源和 MyBatis Plus:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/hero_springboot_demo?useUnicode=true&characterEncoding=utf8&useSSL=true
username: root
password: Mysql.123
# mybatis 日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
5.2 DemoApplication
在启动类 DemoApplication下配置 Mapper 扫描路径:
@MapperScan("com.yygnb.demo.mapper")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
6 测试运行
至此,整合MyBatisPlus就完成了,启动服务,分别测试五个接口。由于还没有整合接口文档,可以先在 postman 或其他工具中测试。postman 使用的人较多,也比较简单。这里我就采用 IDEA 内置的 HTTP Client 进行测试。
点击顶部 "Tools" --> "HTTP Client" --> "Create request in HTTP Client",会打开“rest-api.http”,在该界面可以编写请求。点击右上角的 "Add request" 可添加新请求。 多个请求之间,需要使用 ### 分隔。点击请求左侧的绿色三角便可执行请求。

POST http://localhost:9099/computer
Content-Type: application/json
{
"id": "",
"size": "18",
"operation": "Linux",
"year": "2023"
}
###
PUT http://localhost:9099/computer/13
Content-Type: application/json
{
"id": "",
"size": "0",
"operation": "Linux",
"year": "2013"
}
###
DELETE http://localhost:9099/computer/13
###
GET http://localhost:9099/computer/13
###
GET http://localhost:9099/computer/find-page/2/10
###
虽然集成 MyBatis Plus 实现了增删改查接口,但上面的代码还存在很多问题:
- 数据库的版本管理
- 接口的参数校验和全局异常处理
- 日志
- 接口文档
- 数据库连接池信息监控
- 多环境配置
- 服务运行状态监控等
上述问题都会在后续的文章中逐步完善demo。
今日优雅哥(youyacoder)学习结束,期待关注留言分享~~
SpringBoot 如何集成 MyBatisPlus - SpringBoot 2.7.2实战基础的更多相关文章
- spring-cloud集成mybatis-plus
mybatis-plus插件是对mybatis做出系列增强插件,后面简称MP,MP可免去开发者重复编写xml.mapper.service.entity等代码,通过MP提供的实体注解来完成单表的CRU ...
- springboot集成mybatisplus小例子
集成mybatisplus后,简单的CRUD就不用写了,如果没有特别的sql,就可以不用mapper的xml文件的. 目录 pom.xml文件 <?xml version="1.0&q ...
- SpringBoot集成MybatisPlus报错
SpringBoot集成MybatisPlus报错 启动的时候总是报如下错误: java.lang.annotation.AnnotationFormatError: Invalid default: ...
- SpringBoot图文教程11—从此不写mapper文件「SpringBoot集成MybatisPlus」
有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1「概念+ ...
- 13 — springboot集成mybatis-plus — 更新完毕
1.mybatis-plus需要掌握的知识 1).mybatis-plus是什么? 不写了,老衲一般都是直接进官网 mybatis-plus官网地址:https://baomidou.com/guid ...
- SpringBoot集成MyBatis-Plus代码生成器(Dao)
1.说明 本文基于SpringBoot集成MyBatis-Plus代码生成器, 把原来生成Entity.Mapper.Mapper XML.Service.Controller等各个模块的代码, 修改 ...
- SpringBoot集成MyBatis-Plus代码生成器
1.说明 本文详细介绍Spring Boot集成MyBatis-Plus代码生成器的方法. 基于一个创建好的Spring Boot工程, 执行MyBatis-Plus提供的AutoGenerator代 ...
- SpringBoot集成MyBatis-Plus框架
1.说明 本文介绍Spring Boot集成MyBatis-Plus框架, 重点介绍需要注意的地方, 是SpringBoot集成MyBatis-Plus框架详细方法 这篇文章的脱水版, 主要是三个步骤 ...
- SpringBoot集成MyBatis-Plus框架详细方法
1.说明 本文详细介绍Spring Boot集成MyBatis-Plus框架的方法, 使用MySQL数据库进行测试, 包括完整的开发到测试步骤, 从一开始的Spring Boot工程创建, 到MySQ ...
随机推荐
- 【动态UAC权限】无盾程序(win32&cmd)
可以看到两种不同的提权方式,注意是动态,用代码提权,而不是用清单文件提前处理. 函数都写好了,这里不多做解释. win32程序: 首先需要这俩头文件,第二个我忘了啥函数要用了,总之出问题加上就对了:( ...
- Django+Vue+Nginx+Https域名代理访问
Django+Vue使用Nginx实现Https域名的安全访问 前端 VUE 前端访问自身域名: https://demo.com,后序使用 Nginx 代理至后端 直接访问后端https:api会无 ...
- SQL中的数字、字母和汉字
知识点001 当变量的数据类型为VARCHAR时,变量赋值后,变量中的字符所占字节数,数字和字母是1个bytes,汉字是2个bytes; 当变量的数据类型为NVARCHAR时,变量赋值后,变量中的字符 ...
- MTK 平台sensor arch 介绍-hal
MTK 平台sensor arch 介绍-hal 一:整体框架 二:具体流程简介 AP-HAL: (1)init & control flow 我们以前文的originchannel 的 ac ...
- Python的关键字参数与斜杠“/”
Python3.8 新增了一种语法,可以使用斜杠 / 占据一个参数的位置,表示在此之前的参数都只接受位置参数的传参形式. 例如,对以下函数声明: def func(a, b, /, c, d, *, ...
- 花两万培训Java的三个同学,最后都怎么样了
仙路尽头谁为峰,学完Java学Python. 前言 对于IT行业的培训,例如Java.大数据.H5等等,我一直保持着肯定的态度. 因为当年大学时期的我,也差点去参加Java培训.一是因为那时钱包空空, ...
- 13. L1,L2范数
讲的言简意赅,本人懒,顺手转载过来:https://www.cnblogs.com/lhfhaifeng/p/10671349.html
- printf 输出前导0
printf ("%3d\n", 5); printf ("%03d\n", 5); 输出为
- JavaScript Object学习笔记二
Object.create(proto, [propertiesObject])//创建对象,使用参数一来作为新创建对象的__proto__属性,返回值为在指定原型对象上添加自身属性后的对象 //参数 ...
- SpringCloud微服务实战——搭建企业级开发框架(四十二):集成分布式任务调度平台XXL-JOB,实现定时任务功能
定时任务几乎是每个业务系统必不可少的功能,计算到期时间.过期时间等,定时触发某项任务操作.在使用单体应用时,基本使用Spring提供的注解即可实现定时任务,而在使用微服务集群时,这种方式就要考虑添 ...