MyBaits-Plus目录
一、概述
MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1、特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
二、MP程序测试
1、项目搭建
步骤:
1、搭建数据库
-- 创建数据库
CREATE DATABASE `mybatis-plus`
-- 切换数据库
USE `mybatis-plus`
-- 创建用户表
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)
);
-- 插入信息
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');
2、创建SpringBoot项目并导入相关依赖
注意: 尽量不要同时导入MyBatis和MyBatis-Plus的依赖、可能会出现版本冲突问题。
<dependencies>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3、配置数据库连接,properties文件
注意:如果使用MySql8版本的需要注意与MySql5的驱动不同,同时要增加时区配置,这里使用MySql8。
# mysql 8 驱动不同,增加时区
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-plus?serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=root
# mysql 5
# spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-plus
4、创建包 / 实体类
这里使用的Lombok插件,只需添加以下注解即可生成get/set、toString,有参无参方法等。
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
5、创建包 / mapper接口
说明:
- 要在对应的mapper接口中继承BaseMapper类
- 泛型值传入的对象
- 添加@Repository 或 @Mapper 注解,代表为持久层。
@Repository
public interface UserMapper extends BaseMapper<User> {
}
6、在主启动类上添加扫描Mapper的注解
@MapperScan(“mapper接口的包位置r”)
@MapperScan("com.plus.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
2、selectList 方法
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
// 参数Wrapper:条件构造器,暂时不用
// 查询全部
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
所有基本常用方法都来自继承的BaseMapper类,也可以在mapper接口中定义指定的方法。
查看运行结果:
2.1、配置日志
我们想看运行的SQL是什么样子的,需要配置日志。
# 配置日志(默认控制台输出)
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
再次运行查看结果:
3、insert 方法
@Test
void testInsert(){
User user = new User();
user.setName("周公瑾");
user.setAge(20);
user.setEmail("123456@qq.com");
int row = userMapper.insert(user);
System.out.println(row + "\n" + user);
}
查看SQL结果:
可以看到ID是MP自动生成的。
3.1、主键生成策略
实体类id对应数据库中的主键生成策略有(uuid、自增id、雪花算法、redis)
- 自增:分库分表时要在一张表最后面的值加一。
- UUID:每次生成随机唯一的值,同时随机生成的值太多不方便排序。
- Redis:原子操作实现
- MP自带策略:通过雪花算法实现,每次值不同。
配置主键自增:
- 在实体类要自增的属性上添加注解:
@TableId(type = IdType.AUTO)
- 需要保证数据库字段一定是自增!
- 测试插入
@TableId(type = IdType.AUTO)
private Long id;
源码:
package com.baomidou.mybatisplus.annotation;
import lombok.Getter;
/**
* 生成ID类型枚举类
*/
@Getter
public enum IdType {
/**
* 数据库ID自增
* 该类型请确保数据库设置了 ID自增 否则无效
*/
AUTO(0),
/**
* 该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
*/
NONE(1),
/**
* 用户输入ID
* 该类型可以通过自己注册自动填充插件进行填充
*/
INPUT(2),
/* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */
/**
* 分配ID (主键类型为number或string),
* 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(雪花算法)
*/
ASSIGN_ID(3),
/**
* 分配UUID (主键类型为 string)
* 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(UUID.replace("-",""))
*/
ASSIGN_UUID(4),
ID_WORKER(3),
ID_WORKER_STR(3),
UUID(4);
private final int key;
IdType(int key) {
this.key = key;
}
}
雪花算法介绍
SnowFlake 算法,是 Twitter 开源的分布式 id 生成算法。其核心思想就是:使用一个 64 bit 的 long 型的数字作为全局唯一 id。在分布式系统中的应用十分广泛,且ID 引入了时间戳,基本上保持自增的 。
4、update
@Test
void testUpdate() {
User user = new User();
user.setId(1346409041650515970L);
user.setName("周瑜");
user.setAge(21);
userMapper.updateById(user);
}
所有sql会通过调节帮我们动态配置。
4.1、自动填充
开发中需要知道一条insert语句的添加时间 和 update语句的修改时间,通常会在数据库表字段添加: 创建时间 gmt_create 和 修改时间 gmt_modified 、同时这些字段需要自动化。
常用方式:修改代码实现自动化
1、在数据库表中添加字段:create_time、update_time
ALTER TABLE `user`
ADD COLUMN `create_time` datetime NOT NULL
ADD COLUMN `update_time` datetime NOT NULL
2、同步实体类属性
private Date createTime;
private Date updateTime;
3、在属性上添加相应注解
@TableField(fill = FieldFill.INSERT) // 插入时
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) // 修改时
private Date updateTime;
4、配置元数据处理器
@Slf4j // 添加日志
@Component // 交给SpringIOC管理
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
- 编写类并实现MetaObjectHandler类
- 重写插入insertFill和updateFill更新时的填充策略方法
- 将该类交给Spring管理和添加日志
@Component
@Slf4j
- 打印日志信息
log.info("start ... ");
setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
- 参数:fieldName 自动填充的字段名;fieldVal 要插入的字段值;metaObject 给那个数据处理;
5、测试添加和修改
4.2、乐观锁
乐观锁:无论干什么操作、不上锁、不会考虑失败、出了错误再次测试。
悲观锁:无论干什么操作、都上锁、经常考虑失败、出了错误不会测试。
要求:在更新一条记录时,希望这条记录没有被别人抢先更新。
比如:如果在多线程的情况下A线程要对表中的一条数据做更新、而B线程抢先在A线程之前把数据修改了,而这样会导致A线程在更新这条数据时会失败。
乐观锁实现方式:
- 在数据库表中添加version字段、int类型、默认值为1;
- 同步实体类属性 并 添加乐观锁注解
@Version
@Version
private Integer version;
- 注册乐观锁组件
@EnableTransactionManagement // 开启事务管理
@Configuration // 配置类
public class MyBatisPlusConfig {
// 注册乐观锁;进行所有操作时进行拦截,然后进行自动化处理 旧版本
// 注册乐观锁插件(新版:3.4.0)
@Bean
public MybatisPlusInterceptor myBatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
4.测试修改成功乐观锁
// 测试乐观锁成功
@Test
void testLock(){
// 1、查询根据id获取用户信息
User user = userMapper.selectById(1L);
// 2、修改用户信息
user.setName("张三三");
// 3、修改
userMapper.updateById(user);
}
查看使用乐观锁修改成功的结果:
在单线程的情况下、MP会自动将version带上、会将原version进行对比、修改成功后+1
5.测试修改失败乐观锁
如果没有乐观锁会覆盖插队线程的值;
@Test
void testLock2(){
// 线程A
User user = userMapper.selectById(1L);
user.setName("张三三1");
// 线程B
User user2 = userMapper.selectById(1L);
user2.setName("张三三2");
userMapper.updateById(user2);
userMapper.updateById(user);
}
5、查询常用方法
5.1、selectById(int)
只获取一条信息通过:selectById(int)方法
通过ID查询当前一个用户信息
@Test
void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user.toString());
}
5.2、selectBatchIds(集合)
通过集合获取批量信息,通过:selectBatchIds(集合)方法
通过多个ID查询批量用户信息
@Test
void testSelectBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
5.3、selectByMap(map)
通过定义map实现自定义条件查询:selectByMap( map ) 方法
@Test
void testSelectByMap(){
HashMap<String, Object> map = new HashMap<>();
// 自定义查询条件
map.put("email", "123456@qq.com");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
5.4、分页查询
步骤:
1、配置分页插件
// 注册乐观锁插件(新版:3.4.0)
@Bean
public MybatisPlusInterceptor myBatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
// DbType:数据库类型(根据类型获取应使用的分页方言)
// 分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
2、测试分页
@Test
void testPage(){
// page current:当前页;size 页面大小
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page, null);
// 打印记录
page.getRecords().forEach(System.out::println);
}
Page类方法:
// page current:当前页;size 页面大小
Page<User> page = new Page<>(current ,size);
page.getTotal(); // 总数量
page.hasPrevious(); // 是否有上一页
page.hasNext(); // 是否有下一页
page.getSize(); // 获取大小
page.getCurrent(); // 当前参数
page.getRecords(); // 获取所有记录
6、delete
6.1、deleteById(int)
通过int值进行单个删除
@Test
void testDelete(){
userMapper.deleteById(1346409041650515971L);
}
6.2、其它方法进行删除
// 多个ID进行批量删除
deleteBatchIds(Arrays.asList(id1,id2,id3));
// 条件删除
HashMap<String, Object> map = new HashMap<>();
map.put("name", "value");
userMapper.deleteByMap(map);
6.3、逻辑删除
- 物理删除:直接从数据库中删除
- 逻辑删除:没有从数据库中删除,通过变量让它失效。
- 逻辑删除的作用:管理员可查看被删除的记录,防止数据丢失。
实现方式:
1、在数据库表中添加字段:deleted、int类型、默认值为0;
2、同步实体类并添加逻辑删除注解
@TableLogic
private Integer deleted;
3、配置逻辑删除组件,在properties文件中配置。
注意:如果MP版本是3.4.0+版本配置以下即可,如果版本比较低还需要注册;
# 配置逻辑删除 ,1已被删除的值;0没有被删除的值
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
4、测试逻辑删除(删除1号用户)
@Test
void testDelete2(){
userMapper.deleteById(1L);
}
查看执行结果:
执行逻辑删除,并不是真正的删除,而是将数据库表中deleted字段的默认值0改为1,那么在查询时是否可以查到该用户呢?
5、测试查询 1号 用户
在查询1号用户时执行的SQL会动态的将deleted=0该条件加上,结果为0
三、Wrapper条件构造器
Wrapper :上面的方法只能执行简单的SQL、而Wrapper类可执行复杂的SQL;
测试:
1、isNotNull
查询多条数据:selectList( wrapper ) 返回List
例子:查询name不为空的用户 并且 邮箱不为空 年龄大于等于20
@Test
void t1(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age", 20);
userMapper.selectList(wrapper).forEach(System.out::println);
}
2、eq
查询一条数据:selectOne( wrapper ) 返回一个对象;
查询指定字段的值;
@Test
void t2(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "周瑜");
userMapper.selectOne(wrapper);
}
3、between
查询结果数量:selectCount( wrapper ) 返回Internet类型数据
区间查询:年龄在18-25之间的数量
@Test
void t3(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age", 18,25);
userMapper.selectCount(wrapper); // 查询结果数
}
4、notLike
模糊查询:查询name中不包含a的 并且 email 以t右边开头
@Test
void t4(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.notLike("name", "a")
.likeRight("email", "t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
5、inSql
@Test
void t5(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// id 在子查询中查出来
wrapper.inSql("id", "select id from user where id < 20");
userMapper.selectObjs(wrapper); // 查询一些对象
}
6、orderByDesc
**排序查询:**通过ID进行降序
@Test
void t6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
四、代码生成器
注意: MyBatis-Plus 从
3.0.3
之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:
<!-- 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!-- 模板引擎(默认) -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
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 MyCodeAutoGenerator {
public static void main(String[] args) {
// 创建代码生成器对象
AutoGenerator autoGenerator = new AutoGenerator();
// 1、全局配置
GlobalConfig gC = new GlobalConfig();
// 获取当前项目目录
String projectPath = System.getProperty("user.dir");
gC.setOutputDir(projectPath+"/src/main/java"); // 代码要生成到那个目录
// 设置作者
gC.setAuthor("Lomus");
// 是否打开资源管理器
gC.setOpen(false);
// 是否覆盖原来生成的
gC.setFileOverride(false);
// 去掉service的I前缀
// gC.setServiceName("%sService");
// ID生成策略
gC.setIdType(IdType.AUTO);
// 设置日期类型
gC.setDateType(DateType.ONLY_DATE);
// 是否配置Swagger文档
// gC.setSwagger2(true);
// 将全局配置放入自动生成器中
autoGenerator.setGlobalConfig(gC);
// 2、设置数据源 要改
DataSourceConfig dataSource = new DataSourceConfig();
dataSource.setDriverName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT");
dataSource.setUsername("root");
dataSource.setPassword("密码");
dataSource.setDbType(DbType.MYSQL);
autoGenerator.setDataSource(dataSource);
// 3、设置生成那些包
PackageConfig pC = new PackageConfig();
// 设置模块名
pC.setModuleName("stu");
// 类放入那个包下
pC.setParent("com.plus");
pC.setEntity("entity");
pC.setMapper("mapper");
pC.setService("service");
pC.setController("controller");
// 设置包
autoGenerator.setPackageInfo(pC);
// 4、策略配置
StrategyConfig strategy = new StrategyConfig();
// 设置要映射的表 ... 可用逗号隔开 要改的地方
strategy.setInclude("student");
// 设置包的命名规则(下划线转驼峰)
strategy.setNaming(NamingStrategy.underline_to_camel);
// 设置列的名字
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 是否使用Lombok的注解
strategy.setEntityLombokModel(true);
// 设置逻辑删除
strategy.setLogicDeleteFieldName("deleted");
// 设置自动填充
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified",FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
// 设置乐观锁
strategy.setVersionFieldName("version");
// 设置驼峰命名
strategy.setRestControllerStyle(true);
// 设置URL请求字段转换为下划线命名
strategy.setControllerMappingHyphenStyle(true);
// 策略
autoGenerator.setStrategy(strategy);
// 执行
autoGenerator.execute();
}
}
五、其它
关于低版本的注册配置,由于性能分页插件 在 MP3.2.0 后,性能分析插件被移除了,官方推荐使用第三方性能分析插件。
// 注册乐观锁;进行所有操作时进行拦截,然后进行自动化处理 3.3.0-版本
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
本文参考于哔哩哔哩UP主:狂神说MyBatis-Plus章节和MyBatis-Plus官方文档