简介
MyBatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。


我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。

特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
框架结构

快速入门
1.创建一个mybatis_plus
的数据库(自定义)
2.创建一张User
表
现有一张 User
表,其表结构如下:
id | name | age | |
---|---|---|---|
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 |
其对应的数据库 Schema 脚本如下:
sql
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)
);
其对应的数据库 Data 脚本如下:
sql
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');
将其运行建表,并给表中插入数据。


3.创建一个空的 Spring Boot 工程。导入依赖
xml
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--mybatis-plus mybatis-plus自己开发的,非官方的-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>

注意:我们使用 mybatis-plus 可以节省我们大量的代码,尽量不要同时导入 mybatis 和 mybatisplus!mybatisplus包含mybatis的依赖。
4.编写配置文件连接数据库

ini
# 配置数据库
spring.datasource.username=root
spring.datasource.password=kylin
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
传统方式pojo-dao(连接mybatis,配置mapper.xml文件)service-controller
5.使用了mybatis-plus 之后。(本例直接在测试类测试)
-
pojo
less@Data @AllArgsConstructor @NoArgsConstructor public class User { //对应数据库中的主键(uuid,自增id,雪花算法,redis,zookeeper) @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; private String email; }
-
mapper接口
java//在对应的Mapper上面继承基本的类 BaseMapper @Repository//代表是持久层的 Spring的注解 //@Mapper mybatis的注解 public interface UserMapper extends BaseMapper<User> { }
注意:我们需要在主启动类上去扫描我们的mapper包下的所有接口。
@MapperScan
6.测试类中进行测试
查询所有用户


测试成功~
Mapper CRUD 接口

Insert

Delete

Update

Select


配置日志
我们现在所有的sql现在是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志。配置配置文件开启日志输出。

ini
# 配置日志 控制台输出
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
查看测试查询全部效果

插入操作
userMapper.insert();
参数是实体类对象

scss
// 测试插入
@Test
void testInsert() {
User user = new User();
user.setName("kylin");
user.setAge(3);
user.setEmail("zhang171346168@qq.com");
int result = userMapper.insert(user);//id会自动生成全局唯一id
System.out.println(result);
}
运行测试

发现自动帮我们生成一个全局唯一主键ID值!

主键生成策略
由上可知,当我们不配主键ID时,MyBatisPlus会帮我们自动生成一个全局唯一的主键值。哪它是按什么思路生成的呢?我们能配置主键生成策略吗?答案是可以的。
我们可以通过在实体类上的 @TableId进行配置生成策略
值 | 描述 |
---|---|
AUTO | 数据库ID自增 |
NONE | 无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT) |
INPUT | insert前自行set主键值 |
ASSIGN_ID | 分配ID(主键类型为Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator 的方法nextId (默认实现类为DefaultIdentifierGenerator 雪花算法) |
ASSIGN_UUID | 分配UUID,主键类型为String(since 3.3.0),使用接口IdentifierGenerator 的方法nextUUID (默认default方法) |
ID_WORKER | 分布式全局唯一ID 长整型类型(please use ASSIGN_ID ) |
UUID | 32位UUID字符串(please use ASSIGN_UUID ) |
ID_WORKER_STR | 分布式全局唯一ID 字符串类型(please use ASSIGN_ID ) |
默认值为ID_WORKER 全局唯一id。也就是上文生成的。(MyBatisPlus新版发生改变例如3.3.1)

其采用的算法是雪花算法
snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为 毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味 着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯 一!
主键自增
以配置主键自增为例。
1.首先我们要在实体类主键字段上加上@TableId(type = IdType.AUTO)

2.主键自增需要修改数据库字段为自增

3.再次测试插入


此时的ID值则在原来去基础上自增1.其他主键策略修改type值就可以了。
更新操作
userMapper.updateById();
注意参数是实体类对象,通过id作为条件进行更新
测试之前将主键生成策略改为input手动输入

编写测试

ini
@Test
void testUpdate() {
User user = new User();
user.setId(5L);
user.setName("kylin");
user.setAge(12);
user.setEmail("zhang171346168@qq.com");
int i = userMapper.updateById(user);
System.out.println(i);
}


自动填充
创建时间、修改时间!这些个操作一遍都是自动化完成的,我们不希望手动更新!
阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上!而且需 要自动化!
{% note success %}
方式一:数据库级别(工作中不允许你修改数据库)
{% endnote %}
1、在表中新增字段 create_time, update_time


2.再次测试插入方法前,我们需要先把实体类的属性与字段同步!


MyBatisPlus是默认开启驼峰命名的。也就是实体类中属性createTime对应字段create_time。如果数据库中为create_time为createTime则会出现映射错误。
如果出现上面这种情况则需要配置MyBatisPlus的配置文件。关闭驼峰命名
arduino
mybatis-plus.configuration.map-underscore-to-camel-case=false
测试插入方法


3.插入成功后查看数据库

发现数据库中已经更新了创建时间和更新时间。
注意:SpringBoot配置数据库时时区为UTC会造成写入数据库时与中国北京时间相差8小时。这时候我们就要修改时区为serverTimezone=GMT%2B8

{% note success %}
方式二:代码级别
{% endnote %}
1.删除数据库的默认值、更新操作!(navicat中把这两栏删掉,再重新创建)

2.实体类字段属性上需要增加注解@TableField
根据实际情况。updateTime应在对其进行任何操作时都要更新时间。所以要在插入和更新时都更新改字段。


3.编写处理器来处理这个注解,在handle包下创建一个MyMetaObjectHandler 类实现 MetaObjectHandler接口,重写方法。

4、测试插入



5.测试更新


查看数据库发现改用户的更新时间发生改变。成功!

乐观锁
{% note info %} 乐观锁 : 故名思意十分乐观,它总是认为不会出现问题,无论干什么不去上锁!如果出现了问题, 再次更新值测试。 {% endnote %}
{% note warning %} 悲观锁:故名思意十分悲观,它总是认为总是出现问题,无论干什么都会上锁!再去操作! {% endnote %}
乐观锁实现方式
- 取出记录时,获取当前 version
- 更新时,带上这个version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果version不对,就更新失败

{% note success %}
乐观锁插件测试
{% endnote %}
1.给数据库中增加version字段!


2.我们实体类加对应的字段。使用@Version
注解


3.编写MybatisPlus配置类,注册组件。

less
//@MapperScan("com.kylin.mapper")//扫描mapper文件夹
@EnableTransactionManagement//自动管理事务
@Configuration//配置类
public class MybatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
4.测试一下

csharp
//测试乐观锁
@Test
void testOptimisticLocker() {
//1.查询用户信息
User user = userMapper.selectById(1L);
//2.修改用户信息
user.setName("kylin");
user.setEmail("zhang171346168@qq.com");
//3.执行更新操作
int i = userMapper.updateById(user);
System.out.println(i);
}


正常更新~
5.模拟另一个线程执行了插队操作测试

scss
//测试乐观锁失败~多线程下
@Test
void testOptimisticLocker2() {
//线程1
User user = userMapper.selectById(1L);
user.setName("kylin111");
user.setEmail("zhang171346168@qq.com");
//模拟另一个线程执行了插队操作
User user2 = userMapper.selectById(1L);
user2.setName("kylin222");
user2.setEmail("zhang171346168@qq.com");
//执行更新操作
userMapper.updateById(user2);
userMapper.updateById(user);//如果没有乐观锁就会覆盖插队线程的值
}


查询操作
userMapper.selectById()

csharp
@Test
void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}

批量查询userMapper.selectBatchIds()

csharp
//测试批量查询
@Test
void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1,2,3));
users.forEach(System.out::println);
}

按条件查询之一 通过mapuserMapper.selectByMap()

arduino
//测试条件查询之一 通过map
@Test
void testSelectByBatchIds(){
HashMap<String,Object> map = new HashMap<>();
//自定义查询
map.put("name","kylin");
map.put("age",3);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}

分页查询
进行分页查询可以使用原始的limit进行分页,或者使用pageHelper第三方插件。而MaBatisPlus也内置了分页插件。
1.在MybatisPlus的配置类中注册拦截器组件


typescript
//注册分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
2.测试。直接使用Page对象即可! userMapper.selectPage(page,null);//条件表达式为空

csharp
//测试分页查询
@Test
void testPage(){
//参数一:当前页 参数二:页面大小
Page<User> page = new Page<>(2,5);
userMapper.selectPage(page,null);//条件表达式为空
page.getRecords().forEach(System.out::println);
}


删除操作

根据 id 删除记录userMapper.deleteById()

typescript
//测试删除。根据id删除
@Test
void testDeleteById(){
userMapper.deleteById(1251338727926538241L);
}


通过id批量删除userMapper.deleteBatchIds()

typescript
//通过id批量删除
@Test
void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1251338727926538242L,1251338727926538243L));
}


通过map删除userMapper.deleteByMap()

arduino
//通过map删除
@Test
void testDeleteMap(){
HashMap<String,Object> map = new HashMap<>();
map.put("name","kylin222");
userMapper.deleteByMap(map);
}


逻辑删除
{% note info %} 物理删除 :从数据库中直接移除
逻辑删除 :再数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1
{% endnote %}
应用场景:管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!
1.在数据表中增加一个 deleted 字段


2.实体类中增加属性。通过@TableLogic

3.在MybatisPlus配置类中注册逻辑删除。3.1.1不用注册Bean


typescript
//逻辑删除组件
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
4.在SpringBoot配置文件中配置逻辑删除的默认值


arduino
#配置逻辑删除 默认为0 逻辑删除后为1
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
5.通过删除操作进行测试



在使用查询全部操作,看看是否能查询到此条记录。


性能分析插件
我们在平时的开发中,会遇到一些慢sql。druid数据源也是有性能分析的。
作用:性能分析拦截器,用于输出每条 SQL 语句及其执行时间 MP也提供性能分析插件,如果超过这个时间就停止运行!
性能分析是需要消耗系统性能的,所以设置当处于开发环境dev,和测试环境test中开启。
1.配置MyBatis配置类注册插件

2.测试。为了展示效果设置了sql语句运行超过1毫米就不执行。随便点击一个测试


使用性能分析插件能帮我们直观的展示Sql语句运行的效率~