MyBatis-Plus

课程介绍

  • 了解MyBatis-Plus
  • 整合MyBatis-Plus
  • 通用CRUD
  • MyBatis-Plus的配置
  • 条件构造器
  • ActiveRecord
  • Mybatis-Plus的插件
  • Sql注入器实现自定义全局操作
  • 自动填充功能
  • 逻辑删除
  • 通用枚举
  • 代码生成器
  • MybatisX快速开发插件

课程目标

  • 了解MyBatis-Plus的作用
  • 掌握MyBatis+MP的整合
  • 掌握Spring+MyBatis+MP的整合
  • 掌握SpringBoot+MyBatis+MP整合
  • 掌握BaseMapper的通用CRUD方法
  • 掌握MP的基本配置
  • 掌握MP的进阶配置
  • 掌握MP的DB策略配置
  • 掌握MP的条件构造器
  • 理解ActiveRecord以及使用
  • 掌握MP的执行分析插件
  • 掌握MP的性能分析插件
  • 掌握MP的乐观锁插件
  • 掌握Sql注入器
  • 掌握自动填充功能
  • 掌握逻辑删除
  • 理解 通用枚举
  • 了解代码生成器
  • 了解MybatisX快速开发插件

了解MyBatis-Plus

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

特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响
  • 损耗小:启动即会自动 注入基本CRUD,性能基本无损耗,直接面向对象操作
  • 强大的CRUD操作:内置通用Mapper、通用Service,仅仅通过少量配置即可实现单表大部分CRUD操作,更有强大的条件构造器,满足各类使用需求
  • 支持Lambda形式调用:通过Lambda表达式,方便的编写各类查询条件,无需担心字段写错
  • 支持各种数据库
  • 支持主键自动生成
  • 支持XML热加载
  • 支持ActiveRecord模式:支持ActiveRecord形式调用,实体类只需继承Model类即可进行强大的CRUD操作
  • 支持自定义全局通用操作
  • 内置代码生成器
  • 内置分页插件
  • 内置性能分析插件
  • 内置全局拦截插件
  • 内置sql注入剥离器

架构

![image-20220104190338844](D:\OneDrive - stu.ahu.edu.cn\blog\MP\MyBatis-Plus.md)

快速开始

对于MyBatis整合MP常常有三种用法,分别是MyBatis+MP、Spring+MyBatis+MP、Spring Boot+MyBatis+MP。

Mybatis实现查询User

==第一步,编写mybatis-config.xml文件==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mp?
useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;allowMultiQueries=true&amp;useS SL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>

==第二步,编写User实体对象,使用lombok进行了进化bean操作==

1
2
3
4
5
6
7
8
9
10
11
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}

==第三步,编写UserMapper接口==

1
2
3
public interface UserMapper {
List<User> findAll();
}

==第四步,编写UserMapper.xml文件==

1
2
3
4
5
<mapper namespace="cn.itcast.mp.simple.mapper.UserMapper">
<select id="findAll" resultType="cn.itcast.mp.simple.pojo.User">
select * from tb_user
</select>
</mapper>

==第五步,编写测试用例==

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
public void testUserList() throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findAll();
for (User user : list) {
System.out.println(user);
}
}

Mybatis+MP实现

==第一步,将UserMapper继承BaseMapper,将拥有了BaseMapper中的所有方法==

1
public interface UserMapper extends BaseMapper<User>

==第二步,使用MP中的MybatisSqlSessionFactoryBuilder进程构建==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void testUserList() throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//这里使用的是MP中的MybatisSqlSessionFactoryBuilder
SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 可以调用BaseMapper中定义的方法
List<User> list = userMapper.selectList(null);
for (User user : list) {
System.out.println(user);
}
}

注意:在User对象中添加@TableName,指定数据库表名

简单说明:由于使用了MybatisSqlSessionFactoryBuilder进行了构建,继承的BaseMapper中的方法就载入到了SqlSession中,所以就可以直接使用相关的方法

Spring+Mybatis+MP

引入了Spring框架,数据源、构建等工作就交给了Spring管理

==第一步,编写jdbc.properties==

==第二步,编写applicationContext.xml==

1
2
3
4
5
6
7
8
9
<!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--扫描mapper接口,使用的依然是Mybatis原生的扫描器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.itcast.mp.simple.mapper"/>
</bean>

==第三步,编写User对象以及UserMapper接口==

==第四步,编写测试用例==

1
2
3
4
5
6
7
8
9
10
11
12
13
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSpringMP {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectList(){
List<User> users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}

SpringBoot+Mybatis+MP

使用SpringBoot将进一步的简化MP的整合,需要注意的是,使用SpringBoot需要继承parent

1
2
3
4
5
6
7
8
9
10
11
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<!--mybatis-plus的springboot支持-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>

==编写启动类==

1
2
3
4
5
6
7
@MapperScan("cn.itcast.mp.mapper") //设置mapper接口的扫描包
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

==编写测试用例==

1
2
3
4
5
6
7
8
9
10
11
12
13
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
List<User> userList = userMapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
}

通用CRUD

前面了解到通过继承BaseMapper就可以获取到各种各样的单表操作,接下来将详细讲解这些操作

@TableField

在MP中通过@TableField注解可以指定字段的一些属性,常常解决的问题有2个

  1. 对象中的属性名和字段名不一致的问题(非驼峰)

    1
    2
    @TableField(value='email')
    private String mail;
  2. 对象中的属性字段在表中不存在的问题

    1
    2
    @TableField(exist = false)
    private String address;

其他用法, 如密码字段不加入查询字段;

更新操作

1
2
3
4
5
6
//根据ID修改
int updateById(@Param(Constants.ENTITY) T entity);
//根据whereEntity条件,更新
//@param entity 实体对象 (set 条件值,可以为 null)
//@param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

删除操作

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
//根据ID删除
int deleteById(Serializable id);
//根据columnMap条件
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

Map<String, Object> columnMap = new HashMap<>();
columnMap.put("age",20);
columnMap.put("name","张三");
//将columnMap中的元素设置为删除的条件,多个之间为and关系
int result = this.userMapper.deleteByMap(columnMap);

//根据entity条件
//@param wrapper 实体对象封装操作类(可以为 null)
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);

User user = new User();
user.setAge(20);
user.setName("张三");
//将实体对象进行包装,包装为操作条件
QueryWrapper<User> wrapper = new QueryWrapper<>(user);
int result = this.userMapper.delete(wrapper);

//根据ID批量删除
//@param idList 主键ID列表(不能为 null 以及 empty)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

//根据id集合批量删除
int result = this.userMapper.deleteBatchIds(Arrays.asList(1L,10L,20L));

查询操作

MP提供了多种查询操作,包括根据id查询、批量查询、查询单条数据、查询列表、分页查询等操作

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
//根据ID查询
T selectById(Serializable id);

//查询(根据ID 批量查询)
//@param idList 主键ID列表(不能为 null 以及 empty)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

//根据 entity 条件,查询一条记录
//@param queryWrapper 实体对象封装操作类(可以为 null)
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.eq("name", "李四");
//根据条件查询一条数据,如果结果超过一条会报错
User user = this.userMapper.selectOne(wrapper);

//根据 Wrapper 条件,查询总记录数
//@param queryWrapper 实体对象封装操作类(可以为 null)
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.gt("age", 23); //年龄大于23岁
Integer count = this.userMapper.selectCount(wrapper);

//根据 entity 条件,查询全部记录
//@param queryWrapper 实体对象封装操作类(可以为 null)
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.gt("age", 23); //年龄大于23岁
//根据条件查询数据
List<User> users = this.userMapper.selectList(wrapper);

//根据 entity 条件,查询全部记录(并翻页)
//@param page 分页查询条件(可以为 RowBounds.DEFAULT)
//@param queryWrapper 实体对象封装操作类(可以为 null)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.gt("age", 20); //年龄大于20岁
Page<User> page = new Page<>(1,1);
//根据条件查询数据
IPage<User> iPage = this.userMapper.selectPage(page, wrapper);
System.out.println("数据总条数:" + iPage.getTotal());
System.out.println("总页数:" + iPage.getPages());
List<User> users = iPage.getRecords();

SQL注入的原理

MP在启动后会将BaseMapper中的一系列的方法注册到meppedStatements中,那么究竟是如 何注入的呢?流程又是怎么样的?

在MP中,ISqlInjector负责SQL的注入工作,它是一个接口,AbstractSqlInjector是它的实现类。在AbstractSqlInjector中,主要是由inspectInject()方法进行注入的,如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Override
public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?>
mapperClass) {
Class<?> modelClass = extractModelClass(mapperClass);
if (modelClass != null) {
String className = mapperClass.toString();
Set<String> mapperRegistryCache =
GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
if (!mapperRegistryCache.contains(className)) {
List<AbstractMethod> methodList = this.getMethodList();
if (CollectionUtils.isNotEmpty(methodList)) {
TableInfo tableInfo = TableInfoHelper.initTableInfo(builderAssistant, modelClass);
// 循环注入自定义方法
methodList.forEach(m -> m.inject(builderAssistant, mapperClass,modelClass,
tableInfo));
} else {
logger.debug(mapperClass.toString() + ", No effective injection methodwas found.");
}
mapperRegistryCache.add(className);
}
}
}

在实现方法中, methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo)); 是关键,循环遍历方法,进行注入。

最终调用抽象方法injectMappedStatement进行真正的注入

1
2
3
4
5
6
7
8
9
10
/**
* 注入自定义 MappedStatement
*
* @param mapperClass mapper 接口
* @param modelClass mapper 泛型
* @param tableInfo 数据库表反射信息
* @return MappedStatement
*/
public abstract MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass,
TableInfo tableInfo);

以SelectById为例查看

1
2
3
4
5
6
7
8
9
10
11
12
public class SelectById extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
SqlMethod sqlMethod = SqlMethod.LOGIC_SELECT_BY_ID;
SqlSource sqlSource = new RawSqlSource(configuration, String.format(sqlMethod.getSql(),
sqlSelectColumns(tableInfo, false),
tableInfo.getTableName(), tableInfo.getKeyColumn(),
tableInfo.getKeyProperty(),
tableInfo.getLogicDeleteSql(true, false)), Object.class);
return this.addSelectMappedStatement(mapperClass, sqlMethod.getMethod(),sqlSource,modelClass, tableInfo);
}
}

可以看到,生成了SqlSource对象,再将SQL通过addSelectMappedStatement方法添加到meppedStatements中

配置

configLocation

如果项目有单独的MyBatis配置,则将其路径配置到configLocation中

Spring Boot

1
mybatis-plus.config-location = classpath:mybatis-config.xml

Spring MVC

1
2
3
4
<bean id="sqlSessionFactory" 				
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

mapperLocations

MyBatis Mapper所对应的XML文件位置

Spring Boot

1
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml

Spring MVC

1
2
3
4
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="mapperLocations" value="classpath*:mybatis/*.xml"/>
</bean>

Maven多模块项目的扫描路径需以classpath*:开头(即加载多个jar包下的XML文件)

typeAliasesPackage

Mybatis别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在Mapper对应的XML文件中可以直接使用类名,而不用使用全限定的类名

Spring Boot

1
mybatis-plus.type-aliases-package = cn.itcast.mp.pojo

Spring MVC

1
2
3
4
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.baomidou.mybatisplus.samples.quickstart.entity"/>
</bean>

mapUnderscoreToCamelCase

  • 类型:boolean
  • 默认值:true

是否开启自动驼峰命名规则映射,即从经典是数据库列名A_COLUMN(下划线命名)到经典Java属性名aColumn(驼峰命名)的类似映射

cacheEnabled

  • 类型:boolean
  • 默认值:true

全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为TRUE

idType

  • 类型: com.baomidou.mybatisplus.annotation.IdType
  • 默认值:ID_WORKER

全局默认主键类型,设置后,即可省略实体对象中的@Table(type=IdType.AUTO)配置

Spring Boot

1
mybatis-plus.global-config.db-config.id-type=auto

SpringMVC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="globalConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<property name="idType" value="AUTO"/>
</bean>
</property>
</bean>
</property>
</bean>

tablePrefix

  • 类型:String
  • 默认值:null

表名前缀,全局配置后可省略@TableName()配置

SpringBoot

1
mybatis-plus.global-config.db-config.table-prefix=tb_

SpringMVC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="globalConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<property name="idType" value="AUTO"/>
<property name="tablePrefix" value="tb_"/>
</bean>
</property>
</bean>
</property>
</bean>

条件构造器

在MP中,Wrapper接口的实现类关系如下

![image-20220105082910236](D:\OneDrive - stu.ahu.edu.cn\blog\MP\1.png)

可以看到,AbstractWrapper和AbstractChainWrapper是重点实现,接下来重点了解AbstractWrapper及其子类

allEq

1
2
3
4
5
6
allEq(Map<R, V> params)
allEq(Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
allEq(BiPredicate<R, V> filter, Map<R, V> params)
allEq(BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)

基本比较操作

  • eq:等于
  • ne:不等于
  • gt:大于
  • ge:大于等于
  • lt:小于
  • le:小于等于
  • between
  • notBetween
  • in
  • notIn

模糊查询

  • like
  • notLike
  • likeLeft
  • likeRight

排序

  • orderBy
  • orderByAsc
  • orderDesc

逻辑查询

  • or
  • and

ActiveRecord

简称AR,属于ORM层,遵循标准的ORM模型:表映射到记录,记录映射到对象,字段映射到对象属性。配合遵循的命名和配置惯例,能够很大程度的快速实现模型的操作,而且简洁易懂

AR的主要思想是:

  • 每个数据库表对应创建一个类,类的每一个对象实例对应于数据库中表的一行记录;通常表的每个字段在类中都有相应的Field
  • AR同时负责把自己持久化,在AR中封装了对数据库的访问,即CURD
  • AR是一种领域模型,封装了部分业务逻辑

开启AR之旅

在MP中,开启AR非常简单,只需要将实体对象继承Model即可

1
2
3
4
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User extends Model<User> {}

根据主键查询

1
2
3
4
5
6
7
8
9
10
11
12
13
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testAR() {
User user = new User();
user.setId(2L);
User user2 = user.selectById();
System.out.println(user2);
}
}

新增数据

1
2
3
4
5
6
7
8
9
10
@Test
public void testAR() {
User user = new User();
user.setName("刘备");
user.setAge(30);
user.setPassword("123456");
user.setUserName("liubei");
user.setEmail("liubei@itcast.cn");
boolean insert = user.insert();
}

更新操作

1
2
3
4
5
6
7
8
@Test
public void testAR() {
User user = new User();
user.setId(8L);
user.setAge(35);
boolean update = user.updateById();
System.out.println(update);
}

删除操作

1
2
3
4
5
6
7
@Test
public void testAR() {
User user = new User();
user.setId(7L);
boolean delete = user.deleteById();
System.out.println(delete);
}

根据条件查询

1
2
3
4
5
6
7
8
9
10
@Test
public void testAR() {
User user = new User();
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.le("age","20");
List<User> users = user.selectList(userQueryWrapper);
for (User user1 : users) {
System.out.println(user1);
}
}

Oracle主键Sequence

在mysql中,主键往往是自增长的 ,这样使用起来比较方便的,如果使用的是Oracle数据库,那么就不能使用自增长了,就得使用Sequence序列生成id值

1
2
3
4
5
6
7
#数据库连接配置
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@192.168.31.81:1521:xe
spring.datasource.username=system
spring.datasource.password=oracle
#id生成策略
mybatis-plus.global-config.db-config.id-type=input

配置序列

使用Oracle的序列需要做2件事情:

==第一,需要配置MP的序列生成器到Spring容器==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
@MapperScan("cn.itcast.mp.mapper") //设置mapper接口的扫描包
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/**
* 序列生成器
*/
@Bean
public OracleKeyGenerator oracleKeyGenerator(){
return new OracleKeyGenerator();
}
}

==第二,在实体对象中指定序列的名称==

1
2
3
4
@KeySequence(value = "SEQ_USER", clazz = Long.class)
public class User{
......
}

插件

Mybatis的插件机制

Mybatis允许在已映射语句执行过程中的某一点进行拦截调用。默认情况下,Mybatis允许使用插件来拦截的方法调用包括

  1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  2. ParameterHandler (getParameterObject, setParameters)
  3. ResultSetHandler (handleResultSets, handleOutputParameters)
  4. StatementHandler (prepare, parameterize, batch, update, query)

可以拦截Executor接口的部分方法,比如update,query,commit,rollback等方法

总体概括为:

  1. 拦截执行器的方法
  2. 拦截参数的处理
  3. 拦截结果集的处理
  4. 拦截Sql语法构建的处理

拦截器示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
//拦截方法,具体业务逻辑编写的位置
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
//创建target对象的代理对象,目的是将当前拦截器加入到该对象中
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
//属性设置
}
}

注入到Spring容器:

1
2
3
4
5
6
7
/**
* 自定义拦截器
*/
@Bean
public MyInterceptor myInterceptor(){
return new MyInterceptor();
}

或者通过xml配置,mybatis-config.xml

1
2
3
4
5
<configuration>
<plugins>
<plugin interceptor="cn.itcast.mp.plugins.MyInterceptor"></plugin>
</plugins>
</configuration>

执行分析插件

在MP中提供了对SQL执行的分析的插件,可用作阻断全表更新、删除的操作,注意:该插件仅用于开发环境,不适用于生产环境

SpringBoot:

1
2
3
4
5
6
7
8
9
@Bean
public SqlExplainInterceptor sqlExplainInterceptor(){
SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor();
List<ISqlParser> sqlParserList = new ArrayList<>();
// 攻击 SQL 阻断解析器、加入解析链
sqlParserList.add(new BlockAttackSqlParser());
sqlExplainInterceptor.setSqlParserList(sqlParserList);
return sqlExplainInterceptor;
}

性能分析插件

性能分析拦截器,用于输出每条SQL语句及其执行时间,可以设置最大执行时间,超过时间会抛出异常

1
2
3
4
5
6
7
8
9
10
<configuration>
<plugins>
<!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor">
<property name="maxTime" value="100" />
<!--SQL是否格式化 默认false-->
<property name="format" value="true" />
</plugin>
</plugins>
</configuration>

乐观锁插件

意图:当要更新一条记录的时候,希望这条记录没有被别人更新

乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时,set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

==插件配置==

spring xml

1
<bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>

spring boot

1
2
3
4
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}

==注解实体字段==

需要为实体字段添加@Version注解

  1. 为表添加version字段,并且设置初始值 为1
  2. 为User实体对象添加version字段,并且添加@Version注解

==特别说明==

  • 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion会回写到entity
  • 仅支持updateById(id) update(entity, wrapper) 方法
  • 在 update(entity, wrapper) 方法下, wrapper 不能复用!!!

Sql注入器

在MP中,通过AbstractSqlInjector将BaseMapper中的方法注入到了Mybatis容器,这样这些方法才可以正常执行

==那么,如何扩充BaseMapper中的方法,该如何实现呢?==

编写MyBaseMapper

1
2
3
4
5
6
7
8
public interface MyBaseMapper<T> extends BaseMapper<T> {
List<T> findAll();
}

//其他的Mapper都可以继承该Mapper,这样实现了统一的扩展 ,比如
public interface UserMapper extends MyBaseMapper<User> {
User findById(Long id);
}

编写MySqlInjector

如果直接继承AbstractSqlInjector的话,原有的BaseMapper中的方法将失效,所以选择继承DefaultSqlInjector进行扩展

1
2
3
4
5
6
7
8
9
10
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList() {
List<AbstractMethod> methodList = super.getMethodList();
methodList.add(new FindAll());
// 再扩充自定义的方法
list.add(new FindAll());
return methodList;
}
}

编写FindAll

1
2
3
4
5
6
7
8
9
public class FindAll extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
String sqlMethod = "findAll";
String sql = "select * from " + tableInfo.getTableName();
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addSelectMappedStatement(mapperClass, sqlMethod, sqlSource, modelClass, tableInfo);
}
}

注册到Spring容器

1
2
3
4
5
6
7
/**
* 自定义SQL注入器
*/
@Bean
public MySqlInjector mySqlInjector(){
return new MySqlInjector();
}

至此,完成了全局扩展SQL注入器

自动填充功能

有时我们需要插入或更新数据时,有些字段能够自动填充数据,比如密码、version等。在MP中提供了这样的功能,可以实现自动填充。

添加@TableField注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@TableField(fill = FieldFill.INSERT) //插入数据时进行填充
private String password;

//FieldFill提供了多种模式选择
public enum FieldFill {
/**
* 默认不处理
*/
DEFAULT,
/**
* 插入时填充字段
*/
INSERT,
/**
* 更新时填充字段
*/
UPDATE,
/**
* 插入和更新时填充字段
*/
INSERT_UPDATE
}

编写MyMetaObjectHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
Object password = getFieldValByName("password", metaObject);
if(null == password){
//字段为空,可以进行填充
setFieldValByName("password", "123456", metaObject);
}
}
@Override
public void updateFill(MetaObject metaObject) {
}
}

逻辑删除

开发系统时,有时候在实现功能时,删除操作需要实现逻辑删除,所谓逻辑删除就是将数据标记为删除,而并非真正 的物理删除(非DELETE操作),查询时需要携带状态条件,确保被标记的数据不被查询到。这样做的目的就是避免 数据被真正的删除。

MP就提供了这样的功能,方便我们使用

修改表结构

为tb_user表增加deleted字段,用于表示数据是否被删除,1代表删除,0代表未删除。

1
2
3
ALTER TABLE `tb_user`
ADD COLUMN `deleted` int(1) NULL DEFAULT 0 COMMENT '1代表删除,0代表未删除' AFTER
`version`;

同时,也修改User实体,增加deleted属性并且添加@TableLogic注解

1
2
@TableLogic
private Integer deleted;

配置

application.properties

1
2
3
4
# 逻辑已删除值(默认为 1)
mybatis-plus.global-config.db-config.logic-delete-value=1
# 逻辑未删除值(默认为 0)
mybatis-plus.global-config.db-config.logic-not-delete-value=0