Mybatis-Plus
Mybatis-Plus
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用(自动生成代码)
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
- 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
HelloWorld
使用第三方组件:
- 导入相应依赖
- 研究依赖如何配置
- 代码如何编写
- 提高扩展技术能力
步骤
- 创建数据库
mybatis_plus
create database mybatis_plus;
- 创建
User
表并插入数据
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
Spring Boot
初始化,导入依赖
- SpringBoot版本:
2.2.5.RELEASE
<!--1.数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--2.lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--3.mybatis-plus 版本很重要3.0.5-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
- 尽量不要同时导入mybatis 和 mybatis-plus,可能存在版本差异问题
- 连接数据库
spring.datasource.username = root
spring.datasource.password = lu123
spring.datasource.url = jdbc:mysql://localhost:3306/mybatis_plus?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
- pojo-dao-service-controller(传统方法)
使用Mybatis-Plus之后
- pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
- mapper
// 在对应的Mapper上面继承基本的接口即可
@Repository // 代表持久层
public interface UserMapper extends BaseMapper<User> {
// 所有的CRUD操作已经编写完成了
// 不需要像以前一样配置一大堆文件
}
- 主程序扫描Mapper
@SpringBootApplication
@MapperScan("com.lu.dao") // 扫描Mapper文件夹
public class MybatisPlus01HelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlus01HelloworldApplication.class, args);
}
}
- 测试
@SpringBootTest
class MybatisPlus01HelloworldApplicationTests {
// 继承了BaseMapper, 所有的方法来自父类, 我们也可以添自己的方法
@Autowired
private UserMapper mapper;
@Test
void contextLoads() {
// 参数是一个Wrapper, 条件构造器, 这里我们先不用, 置为null
// 查询全部用户
List<User> userList = mapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
}
思考
- SQL谁写的?方法哪来的?
- 由Mybatis-Plus集成
日志配置
application.properties添加配置
mybatis-plus.configuration.log-impl = org.apache.ibatis.logging.stdout.StdOutImpl
CRUD扩展
insert
// 测试插入
@Test
public void testInsert() {
User user = new User();
user.setName("lct");
user.setAge(3);
user.setEmail("44@qq.com");
int res = mapper.insert(user); // 自动生成ID
System.out.println(res); // 受影响的行数
System.out.println(user); // id会自动填入
}
主键生成策略
snowflake
-
生成的数据基本可以保证全球唯一
-
@TableId(type = IdType.ID_WORKER) // 对应雪花算法, 默认 private Long id;
主键自增
- 数据库字段要是自增的
@TableId(type = IdType.AUTO)
private Long id;
剩余解释
NONE(1), // 未设置主键
INPUT(2), // 手动输入
UUID(4), // uuid, 全局唯一
ID_WORKER_STR(5); // 雪花算法字符串表示
update
// 测试更新
@Test
public void testUpdate() {
User user = new User();
user.setId(5L);
user.setName("helloWorld");
// 传入的参数是对象
// 通过条件自动拼接动态SQL
int res = mapper.updateById(user);
System.out.println(res);
}
自动填充
- 时间的创建与修改
- gmt_create
- gmt_modified
- 几乎所有表都要配备以上两个字段,且需要自动化
数据库级别
- 工作中不能这样搞
表中新建字段create_time
,update_time
,类型为timestamp
,默认值为CURRENT_TIMESTAMP
更新update_time
列,设置为每次更改后更新时间戳
ALTER TABLE `user`
MODIFY COLUMN `update_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
修改对象字段
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
// 对应数据库中的主键(uuid, 自增id)
@TableId(type = IdType.ID_WORKER)
private Long id;
private String name;
private Integer age;
private String email;
private Date createTime;
private Date updateTime;
}
- 使用上面的insert与update方法进行测试
代码级别
表中新建字段create_time
,update_time
,类型为datetime
,无默认值或附加操作
修改对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
// 对应数据库中的主键(uuid, 自增id)
@TableId(type = IdType.ID_WORKER)
private Long id;
private String name;
private Integer age;
private String email;
// 字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
编写handler处理FieldFill.INSERT
和FieldFill.UPDATE
MyMetaObjectHandler.java
@Component // 记得将组件加到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {
// 插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
// 更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
- 使用上面的insert与update方法进行测试
乐观锁
-
它总是认为不会出现问题,即无论干啥都不上锁;如果出现问题,就再次更新值测试
-
对应字段名:
version
-
实质
- 首先它对应的是修改操作
- 修改时需要先将它查出来,此时对应一个version值
- 修改时判断查出来时的version值是否变化
- 如果变化,则不修改
- 如果没变化,则修改
步骤
数据库添加version
字段,类型为int
,默认值为1
对象增加字段
@Version
private Integer version;
配置乐观锁,新建MybatisPlusConfig.java
@Configuration
@MapperScan("com.lu.dao") // 扫描Mapper文件夹
public class MybatisPlusConfig {
// 注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
测试
- 对应两种情况
- 情况二会更新为
user2
,而user
会因为version
发生变化而失败
// 测试乐观锁成功
@Test
public void testLockerSuccess() {
// 1 查询用户信息
User user = mapper.selectById(1L);
// 2 修改用户信息
user.setName("lct");
// 3 执行更新操作
mapper.updateById(user);
}
// 测试乐观锁失败, 多线程
@Test
public void testLockerFail() {
User user = mapper.selectById(1L);
user.setName("lct");
// 模拟另一个线程插队
User user2 = mapper.selectById(1L);
user2.setName("lct2");
mapper.updateById(user2);
mapper.updateById(user);
}
乐观锁对应的update的SQL语句
UPDATE user SET name=?, age=?, email=?, update_time=?, version=? WHERE id=? AND version=?
select
直接使用mapper的select类操作,直接测试
// 测试批量查询
@Test
public void testSelect() {
List<User> userList = mapper.selectBatchIds(Arrays.asList(1, 2, 3));
userList.forEach(System.out::println);
}
// 测试条件查询
@Test
public void testSelectMap() {
HashMap<String, Object> map = new HashMap<>();
// 自定义查询条件
map.put("name", "lct2");
List<User> userList = mapper.selectByMap(map);
userList.forEach(System.out::println);
}
分页查询
- 使用内置插件
添加分页插件配置
@Configuration
@MapperScan("com.lu.dao") // 扫描Mapper文件夹
public class MybatisPlusConfig {
// 注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
测试
// 测试分页插件
@Test
public void testSelectPage() {
// 参数1: 当前页; 参数2: 页面大小
Page<User> page = new Page<>(2, 2);
mapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
}
delete
// 测试删除
@Test
public void testDelete() {
mapper.deleteById(1685974080317923329L);
}
其他操作与select类似
逻辑删除
物理删除:从数据库中移除
逻辑删除:未在数据库中删除,而是通过一个变量让他失效
步骤
表中新建字段deleted
,类型为int
,默认值为0
,代表未删除
添加对象字段
@TableLogic // 逻辑删除
private Integer deleted;
配置逻辑删除插件
// 逻辑删除插件
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
配置插件
# 配置逻辑删除; 没删除的为0, 删除的为1
mybatis-plus.global-config.db-config.logic-delete-value = 1
mybatis-plus.global-config.db-config.logic-not-delete-value = 0
测试
// 测试逻辑删除
@Test
public void testLogicDelete() {
mapper.deleteById(1L);
System.out.println(mapper.selectById(1L));
}
可以发现配置了逻辑删除后的删除与查询操作都发生了变化
UPDATE user SET deleted=1 WHERE id=? AND deleted=0
SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE id=? AND deleted=0
性能分析插件
测试慢SQL
配置性能分析插件
// 性能分析插件
@Bean
// @Profile({"dev", "test"}) // dev和test环境开启
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor interceptor = new PerformanceInterceptor();
interceptor.setMaxTime(100); // 设置SQL执行最大时间, 超过则不执行
interceptor.setFormat(true); // 格式化输出的SQL
return interceptor;
}
- 简单配置后,即可对SQL执行效率进行评估
- 同时可以将SQL格式化输出,更便于我们查看
条件构造器
写一些复杂SQL(类似于Select中的Map)
通过测试学习
@SpringBootTest
public class WrapperTest {
@Autowired
private UserMapper mapper;
@Test
void contextLoads() {
// 查询name, email不为空且年龄大于等于12
QueryWrapper<User> wrapper = new QueryWrapper<>(); // 和Map类似
wrapper.isNotNull("name")
.isNotNull("email")
.ge("age", 12);
mapper.selectList(wrapper).forEach(System.out::println);
}
@Test
void test02() {
// 查询name=lct
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "lct");
System.out.println(mapper.selectOne(wrapper));
}
@Test
void test03() {
// 查询age在15~20之间的人的个数
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age", 15, 20);
Integer count = mapper.selectCount(wrapper);
System.out.println(count);
}
@Test
void test04() {
// 模糊查询, 名字里有't'
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name", "t") // %t%
.likeRight("email", "t"); // t%
List<Map<String, Object>> list = mapper.selectMaps(wrapper);
list.forEach(System.out::println);
}
@Test
void test05() {
// id 在子查询中查出来
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id", "select id from user where id < 3");
List<Object> objects = mapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
@Test
void test06() {
// id降序排序
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("id");
List<User> userList = mapper.selectList(wrapper);
userList.forEach(System.out::println);
}
}
代码生成器
生成
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
// 代码自动生成器
public class LctCode {
public static void main(String[] args) {
// 构建一个代码生成器对象
AutoGenerator generator = new AutoGenerator();
// 1 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir"); //获取当前目录
gc.setOutputDir(projectPath + "/src/main/java"); // 输出到哪个目录
gc.setAuthor("lct");
gc.setOpen(false);
gc.setFileOverride(false); // 是否覆盖
gc.setServiceName("%sService"); // 去Service的'I'前缀
gc.setIdType(IdType.ID_WORKER);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
generator.setGlobalConfig(gc);
// 2 设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUsername("root");
dsc.setPassword("lu123");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8");
dsc.setDbType(DbType.MYSQL);
generator.setDataSource(dsc);
// 3 包的配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.lu");
pc.setModuleName("user");
pc.setEntity("pojo");
pc.setMapper("dao");
pc.setService("service");
pc.setController("controller");
generator.setPackageInfo(pc);
// 4 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user"); // 设置要映射的表名, 只需改这里就可以
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 是否开启Lombok注解
strategy.setLogicDeleteFieldName("deleted"); // 设置逻辑删除字段
// 4.1 自动填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtUpdate = new TableFill("gmt_update", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtUpdate);
strategy.setTableFillList(tableFills);
// 4.2 乐观锁配置
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true); // 开启RestFul驼峰命名
strategy.setControllerMappingHyphenStyle(true); // .../hello/id/2 --> .../hello_id_2
generator.setStrategy(strategy);
// 5 执行
generator.execute();
}
}
依赖
<!-- 模板引擎 依赖:mybatis-plus代码生成的时候报异常 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<!-- 实体类APIModel报错 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- 前面的依赖 -->
<!-- 1.数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 2.lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- 3.mybatis-plus 版本很重要3.0.5 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
生成结果
└── user
├── controller
│ └── UserController.java
├── dao
│ └── UserMapper.java
├── mapper
│ └── xml
│ └── UserMapper.xml
├── pojo
│ └── User.java
└── service
├── UserService.java
└── impl
└── UserServiceImpl.java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端