该笔记是观看b站up主: 狂神说java 所得。
视频链接:https://www.bilibili.com/video/BV17E411N7KN?from=search&seid=11542808164480111785
简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
框架结构
快速开始
MybatisPlus的版本是 3.0.5
其对应的数据库 Schema 脚本如下:
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 脚本如下:
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 工程
- 导入对应的依赖
<!--mysql数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--MybatisPlus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
导入mybatisplus依赖后就不用导入mybatis依赖了,如果两者都导入的话会造成依赖冲突
user实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private long id;
private String name;
private int age;
private String email;
}
mapper接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
启动类
@MapperScan("com.kuang.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
启动类上需要加@MapperScan(“mapper接口所在的包”)
application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: root
测试
@Autowired
private UserMapper userMapper;
@Test
void findAll() {
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
结果:
配置日志
在application.yml添加配置
# 日志配置
# 输入到控制台
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
测试结果:
CRUD扩展
主键生成策略
注意:
1.默认是ID_WORKER
2.使用这个ID_WORKER 主键类型必须是Long 包装类,其他的类型容易出错
AUTO(0), // 自增,使用这个的话需要将数据库中的主键设置成自增
NONE(1), // 未设置主键
INPUT(2), // 手动输入
ID_WORKER(3), // 全局唯一id
UUID(4), // uuid 全局唯一id
ID_WORKER_STR(5); // ID_WORKER 字符串表示
修改插入时默认生成主键策略
方式一:
在实体类主键上添加@TableId注解
方式二:
在配置文件上进行修改
mybatis-plus:
global-config:
db-config:
# 0:AUTO 1:NONE 2:INPUT 3:ID_WORKER 4:UUID 5:ID_WORKER_STR
id-type: 0
方式二的优先级较低,如果方式一和方式二同时存在的话,最终会使以方式一为准.
如果是共享主键的话, 可以利用这一点进行操作
更新操作
@Test
void updateById() {
User user = new User();
user.setName("李四");
user.setAge(65);
user.setId(7L);
userMapper.updateById(user);
}
这个更新语句参数是对象并且是根据对象中的值动态拼接sql
自动填充
阿里云服务器上的时区需要修改
参考这篇文章:
https://www.cnblogs.com/shiqiangqiang/p/8393662.html
方式一: 数据库级别(不建议)
1.在数据库上新增字段 create_time update_time
结果:
方式二:代码级别 使用mybatisplus提供的自动填充功能
使用注解 @TableField
- 在实体类对应字段上加上注解
@TableField(fill = FieldFill.INSERT) // 添加时生效
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) //添加和修改时生效
private Date updateTime;
2.写个处理器去处理注解
// this.setFieldValByName 需要传入三个参数:需要操作的字段,添加数据,给哪个对象处理
@Slf4j
@Component // 需要将这个处理器加入到IOC容器中
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);
}
/**
* 修改
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
结果:
乐观锁
乐观锁 : 认为不会出现问题,无论干什么都不会去上锁,出问题了再次更新测试
悲观锁 : 认为总是会出现问题,干什么都会上锁
乐观锁实现方式:
- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
乐观锁:1.先查询,获得版本号 version = 1
-- 线程A
update user set name = "zhangsan",version=version+1 where id = 2 and version = 1
-- 线程B 如果该线程抢先执行完成,这个时候version=2,会导致线程A修改失败
update user set name = "zhangsan1",version=version+1 where id = 2 and version = 1
使用乐观锁
-
在数据库表中加上version字段并给上默认值
-
在实体类中添加对应的字段和注解
@Version
private int version;
- 写一个拦截器去配置拦截器组件
@Configuration
@EnableTransactionManagement
public class MyBatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
- 测试
// 模拟线程2抢先线程1执行完成,线程1执行失败,事务回滚
@Test
void save1() {
User user1 = userMapper.selectById(1356172709128667138L);
user1.setName("eqwewqeq");
user1.setAge(4);
User user2 = userMapper.selectById(1356172709128667138L);
user2.setName("daddsadad");
user2.setAge(4);
userMapper.updateById(user2);
userMapper.updateById(user1);
}
结果:
查询操作
根据ID查询
void findById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
结果:
根据ID批量查询
void findBatchById(){
List<User> userList = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
userList.forEach(System.out::println);
}
结果:
条件查询
void findByMap(){
Map<String,Object> map = new HashMap<>();
map.put("name","张三");
List<User> userList = userMapper.selectByMap(map);
userList.forEach(System.out::println);
}
结果:
查询的方法有很多,上面只是列出了常用的
分页查询
- 在拦截器中配置分页组件
@Configuration
@EnableTransactionManagement
public class MyBatisPlusConfig {
/**
* 分页组件
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
- 使用page对象即可
// userMapper.selectPage(page, null)中的null 是填写queryWrapper条件构造器的,如果没有条件的话,可以直接写null
// 第一种写法:
void testPage() {
// page下的 参数一:当前页 参数二:每页查询大小
Page<User> page = new Page<>(1, 5);
IPage<User> iPage = userMapper.selectPage(page, null);
List<User> userList = iPage.getRecords();
System.out.println("总数:" + iPage.getTotal());
userList.forEach(System.out::println);
}
// 第二种写法:
void testPage() {
// page下的 参数一:当前页 参数二:每页查询大小
Page<User> page = new Page<>(1, 5);
userMapper.selectPage(page, null);
List<User> userList = page.getRecords();
System.out.println("总数:" + page.getTotal());
userList.forEach(System.out::println);
}
结果:
删除
物理删除
通过ID进行删除
void testDelete(){
userMapper.deleteById(7L);
}
结果:
批量根据ID删除
@Test
void testBatchByIdDelete(){
userMapper.deleteBatchIds(Arrays.asList(6L,1356150266179727361L));
}
结果:
根据map条件删除
void testByMapDelete(){
Map<String,Object> map = new HashMap<>();
map.put("name","张三1");
userMapper.deleteByMap(map);
}
结果:
逻辑删除
- 在数据表中增加deleted字段,作为删除标识
- 实体类添加对应字段和注解
// 逻辑删除注解
@TableLogic
private Integer deleted;
- 在拦截器中配置逻辑删除组件
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
- 在yml文件中进行配置
mybatis-plus:
global-config:
db-config:
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
5.测试
删除
void testDelete(){
userMapper.deleteById(5L);
}
结果:
查询
// 查询刚才逻辑删除的id
void findById() {
User user = userMapper.selectById(5L);
System.out.println(user);
}
结果:
结果是null,查不到
性能分析插件
- 配置组件
/**
* SQL性能测试插件
*/
@Bean
@Profile({"dev","test"}) // 由于这边配置的是在开发和测试环境下生效,所以需要将application.yml的环境修改成开发或者测试
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); // 设置最大执行时间,超出时间后会报错
performanceInterceptor.setFormat(true); // sql格式化
return performanceInterceptor;
}
spring:
profiles:
active: dev
- 测试:
@Test
void findAll() {
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
这是sql执行时间超出了规定好的最大值,报出的错误
条件构造器
测试一:查询姓名和邮箱都不为空并且年龄是大于等于12岁的用户
void test01(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("name").isNotNull("email").ge("age",12);
List<User> userList = userMapper.selectList(wrapper);
userList.forEach(System.out::println);
}
结果:
测试二:查询名字是张三的用户
void test02(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","张三");
List<User> userList = userMapper.selectList(wrapper);
userList.forEach(System.out::println);
}
结果:
测试三:查询年龄在20~30之间的用户
void test03(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30);
List<User> userList = userMapper.selectList(wrapper);
userList.forEach(System.out::println);
}
结果:
测试四:查询名字里面不包含字母e并且邮箱是字母t开头的
void test04(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.notLike("name","e").likeRight("email","t");
List<User> userList = userMapper.selectList(wrapper);
userList.forEach(System.out::println);
}
结果:
测试五:子查询
void test05(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from user where id < 3");
List<User> userList = userMapper.selectList(wrapper);
userList.forEach(System.out::println);
}
结果:
测试六:通过id降序排序
void test06(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("id");
List<User> userList = userMapper.selectList(wrapper);
userList.forEach(System.out::println);
}
结果:
代码自动生成器
- pom文件中需要添加依赖
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
- 修改配置类并且执行
public class CodeGenerator {
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("作者名"); // 作者名
gc.setOpen(false); // 是否打开资源管理器
gc.setFileOverride(false); // 是否覆盖原来生成的代码
gc.setServiceName("%sService"); // 去掉service接口的I前缀
gc.setIdType(IdType.ID_WORKER); // 设置全局唯一主键
gc.setSwagger2(true); //实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://连接地址/数据库名?useUnicode=true&useSSL=false&characterEncoding=utf8");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("用户名");
dsc.setPassword("密码");
dsc.setDbType(DbType.MYSQL); // mysql数据库
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("模块名"); // 模块
pc.setParent("com.kuang"); // 哪个包下
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("表名1","表名2"); // 设置映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 自动生成lombok
strategy.setLogicDeleteFieldName("deleted"); // 逻辑删除
// 自动填充
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtUpdate = new TableFill("gmt_update", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFields = new ArrayList<>();
tableFields.add(gmtCreate);
tableFields.add(gmtUpdate);
// 乐观锁
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true); // 开启controller层的驼峰命名
strategy.setControllerMappingHyphenStyle(true); // localhost://8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute();
}
}