Pistachiout的博客

每天多学一点知识,就少写一行代码

MyBatis Plus学习笔记

MyBatis Plus

国产的开源框架,基于 MyBatis
在Mybatis-Plus中,内置了代码生成器,我们可以通过该工具,生成我们需要的代码,例如:entity层,controller层,mapper层,service层。如此一来,我么就可以节省编码的时间,优化开发。

MyBatis Plus 快速上手

Spring Boot(2.3.0) + MyBatis Plus(国产的开源框架,并没有接入到 Spring 官方孵化器中)

1、创建 Maven 工程

2、pom.xml 引入 MyBatis Plus 的依赖mybatis-plus-boot-starter

1
2
3
4
5
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>

3、创建实体类

1
2
3
4
5
6
7
8
9
10
package com.mybatisplus.entity;

import lombok.Data;

@Data
public class User {
private Integer id;
private String name;
private Integer age;
}

4、创建 Mapper 接口,继承 BaseMapper,不用自己写代码

1
2
3
4
5
6
7
8
package com.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mybatisplus.entity.User;

public interface UserMapper extends BaseMapper<User> {

}

5、application.yml

1
2
3
4
5
6
7
8
9
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8
username: root
password: root
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

6、启动类main需要添加 @MapperScan(扫描”mapper所在的包”),否则无法加载 Mppaer bean。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.southwind.mybatisplus;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.southwind.mybatisplus.mapper")
public class MybatisplusApplication {

public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}

}

7、测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.southwind.mybatisplus.mapper;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class UserMapperTest {

@Autowired
private UserMapper mapper;

@Test
void test(){
mapper.selectList(null).forEach(System.out::println);
}

}

常用注解

@TableName映射数据库的表名

1
2
3
4
5
6
7
8
9
10
11
12
package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName(value = "user")
public class Account {
private Integer id;
private String name;
private Integer age;
}

@TableId设置主键映射,value 映射主键字段名

type 设置主键的生成策略,如雪花算法或自增等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4),
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
描述
AUTO 数据库自增
NONE MP set 主键,雪花算法实现
INPUT 开发者手动赋值
ASSIGN_ID MP 分配 ID,Long、Integer、String
ASSIGN_UUID 分配 UUID,Strinig

INPUT 如果开发者没有手动赋值,则数据库通过自增的方式给主键赋值,如果开发者手动赋值,则存入该值。

AUTO 默认就是数据库自增,开发者无需赋值。

ASSIGN_ID MP 自动赋值,雪花算法。

ASSIGN_UUID 主键的数据类型必须是 String,自动生成 UUID 进行赋值

@TableField映射非主键字段,value 映射字段名

exist 表示是否为数据库字段 false,如果实体类中的成员变量在数据库中没有对应的字段,则可以使用 exist,VO、DTO

select 表示是否查询该字段

fill 表示是否自动填充,将对象存入数据库的时候,由 MyBatis Plus 自动给某些字段赋值,create_time、update_time

1、给表添加 create_time、update_time 字段

2、实体类中添加成员变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.Date;

@Data
@TableName(value = "user")
public class User {
@TableId
private String id;
@TableField(value = "name",select = false)
private String title;
private Integer age;
@TableField(exist = false)
private String gender;//在数据库中没有该字段
@TableField(fill = FieldFill.INSERT)
private Date createTime;//自动导入创建时间
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;//自动导入更新时间
}

3、创建自动填充处理器,需要实现MetaObjectHandler ,然后重写insertFill()与updateFill()。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.southwind.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
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);
}
}

@Version标记乐观锁

乐观锁:十分乐观,它总是认为不会出现问题,无论干什么都不去上锁! 如果出现了问题,再去上锁。
通过 version 字段来保证数据的安全性,当修改数据的时候,会以 version 作为条件,当条件成立的时候才会修改成功。

乐观锁实现机制:
取出记录时,获取当前 version
更新时,带上这个 version
执行更新时, set version = newVersion where version = oldVersion
如果 version 不对,就更新失败

在这里插入图片描述

1、数据库表添加 version 字段,默认值为 1

2、实体类添加 version 成员变量,并且添加 @Version

1
2
3
@Version
private int version;

3、注册乐观锁配置类optimisticLockerInterceptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.southwind.mybatisplus.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}

}

多线程测试乐观锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
void testOptimisticLocker2(){
//多线程操作乐观锁
//线程1操作,此时 version = 1
User user = userMapper.selectById(4L);
user.setName("66666");
user.setAge(100);
//线程2抢占执行
User user2 = userMapper.selectById(4L);
user2.setName("88888");
user2.setAge(200);
int i2 = userMapper.updateById(user2);
//执行完成后 version 变为 2
System.out.println(i2);
//线程1 继续执行,但是此时发现version = 2,无法满足 version = 1 的要求,无法进行覆盖
//如果没有乐观锁,线程 1 会进行覆盖线程 2 的修改
int i = userMapper.updateById(user);
System.out.println(i);
}

@EnumValue实现枚举

方法1、通用枚举类注解@EnumValue,将数据库字段映射成实体类的枚举类型成员变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.southwind.mybatisplus.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;

public enum StatusEnum {
WORK(1,"上班"),
REST(0,"休息");
StatusEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
@EnumValue
private Integer code;
private String msg;
}
1
private StatusEnum status;

application.yml

1
2
type-enums-package: 
com.southwind.mybatisplus.enums

@TableLogic映射逻辑删除

1、数据表添加 deleted 字段

2、实体类添加注解与对应字段

1
2
@TableLogic
private Integer deleted;

3、application.yml 添加配置

1
2
3
4
global-config:
db-config:
logic-not-delete-value: 0
logic-delete-value: 1

4.配置类

1
2
3
4
5
6
7
8
@Configuration
public class MybatisPlusConfig {
// 逻辑删除注入 3.0.5
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
}

MyBatis-Plus查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
	mapper.selectList(null);//全部查询
QueryWrapper wrapper = new QueryWrapper();
Map<String,Object> map = new HashMap<>();
map.put("name","小红");
map.put("age",3);
wrapper.allEq(map);//等于
wrapper.gt("age",2);//大于
wrapper.ne("name","小红");//不等于
wrapper.ge("age",2);//大于等于

//like '%小'
wrapper.likeLeft("name","小");
//like '小%'
wrapper.likeRight("name","小");

//inSQL
wrapper.inSql("id","select id from user where id < 10");
wrapper.inSql("age","select age from user where age > 3");

wrapper.orderByDesc("age");//排序

wrapper.orderByAsc("age");
wrapper.having("id > 8");

mapper.selectList(wrapper).forEach(System.out::println);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
       System.out.println(mapper.selectById(7));
mapper.selectBatchIds(Arrays.asList(7,8,9)).forEach(System.out::println);

//Map 只能做等值判断,逻辑判断需要使用 Wrapper 来处理
Map<String,Object> map = new HashMap<>();
map.put("id",7);
mapper.selectByMap(map).forEach(System.out::println);

QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",7);
System.out.println(mapper.selectCount(wrapper));
//将查询的结果集封装到Map中
mapper.selectMaps(wrapper).forEach(System.out::println);
System.out.println("-------------------");
mapper.selectList(wrapper).forEach(System.out::println);


分页查询Page

1.配置分页插件

1
2
3
4
5
@Bean
public PaginationInterceptor mypaginationInterceptor() {
return new PaginationInterceptor();
}

2.直接使用page对象进行查询

1
2
3
4
5
6
7
8
9
10
11
		 //参数一 : 当前页
//参数二 : 页面大小
Page<User> page = new Page<>(2,2);
Page<User> result = mapper.selectPage(page,null);
System.out.println(result.getSize());
System.out.println(result.getTotal());
result.getRecords().forEach(System.out::println);
Page<Map<String,Object>> page = new Page<>(1,2);
mapper.selectMapsPage(page,null).getRecords().forEach(System.out::println);
mapper.selectObjs(null).forEach(System.out::println);
System.out.println(mapper.selectOne(wrapper));

自定义 SQL(多表关联查询)

1
2
3
4
5
6
7
8
9
10
11
12
package com.southwind.mybatisplus.entity;

import lombok.Data;

@Data
public class ProductVO {
private Integer category;
private Integer count;
private String description;
private Integer userId;
private String userName;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.southwind.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.southwind.mybatisplus.entity.ProductVO;
import com.southwind.mybatisplus.entity.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper extends BaseMapper<User> {
@Select("select p.*,u.name userName from product p,user u where p.user_id = u.id and u.id = #{id}")
List<ProductVO> productList(Integer id);
}

添加

1
2
3
4
5
User user = new User();
user.setTitle("小明");
user.setAge(22);
mapper.insert(user);
System.out.println(user);

删除

1
2
3
4
5
6
7
8
mapper.deleteById(1);
mapper.deleteBatchIds(Arrays.asList(7,8));
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("age",14);
mapper.delete(wrapper);
Map<String,Object> map = new HashMap<>();
map.put("id",10);
mapper.deleteByMap(map);

修改

1
2
3
4
5
User user = mapper.selectById(1);
user.setTitle("小红");
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("age",22);
mapper.update(user,wrapper);

MyBatisPlus 自动生成

根据数据表自动生成实体类、Mapper、Service、ServiceImpl、Controller

1、pom.xml 导入 MyBatis Plus Generator

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

模板引擎依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beet

2、代码生成程序(注意:一定不能导错包,要用mybatis-plus中的包)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.janson.generate;

import com.baomidou.mybatisplus.annotation.FieldFill;
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.NamingStrategy;

import java.util.ArrayList;
import java.util.List;


/**
* @Author Janson
* @Date 2022/3/15 8:33
* @Version 1.0
*/
public class CodeGenerate {
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("Pistachiout");
gc.setOpen(false);
gc.setFileOverride(false); //是否覆盖
gc.setSwagger2(true); //实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);

// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useSSL=false&useUnicode=true&characterEncoding=utf-8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("11111");
mpg.setDataSource(dsc);

// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("generate");
pc.setParent("com");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setController("controller");
pc.setService("service");
mpg.setPackageInfo(pc);
/*
*/
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true); //自动加上lombok
strategy.setRestControllerStyle(true);
// 公共父类
//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
//strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setInclude("user"); //设置映射表名
strategy.setLogicDeleteFieldName("deleted"); // 逻辑删除
//自动填充
TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
TableFill updateTime = new TableFill("update_time", FieldFill.UPDATE);
List<TableFill> fillList = new ArrayList();
fillList.add(createTime);
fillList.add(updateTime);
strategy.setTableFillList(fillList);
//乐观锁
strategy.setVersionFieldName("version");
//restful风格
strategy.setRestControllerStyle(true);
//localhost:8080/hello_id_1 或者2
strategy.setControllerMappingHyphenStyle(true);
//strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
//mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}

Spring Boot + MyBatis Plus 打包应用,直接发布 阿里云 上云

-------------本文结束感谢您的阅读-------------