简介

特性

无侵入:只做增强不做改变,引入它不会对现有工程产生影响

损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作

强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求

支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多种数据库

支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

支持 XML 热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动

支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作

支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )

支持关键词自动转义:支持数据库关键词(order、key…)自动转义,还可自定义关键词

内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,
支持模板引擎,更有超多自定义配置等您来使用

内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List查询

内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击

架构

image-20210706160448892

案例

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

创建数据库以及表

-- 创建测试表 
-- 创建测试表 
CREATE TABLE `tb_user` (
	`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
	`user_name` varchar(20) NOT NULL COMMENT '用户名',
	`password` varchar(20) NOT NULL COMMENT '密码',
	`name` varchar(30) DEFAULT NULL COMMENT '姓名',
	`age` int(11) DEFAULT NULL COMMENT '年龄',
	`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (`id`)
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARSET = utf8;

INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`
	, `email`)
VALUES ('1', 'zhangsan', '123456', '张三', '18'
	, 'test1@itcast.cn');

INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`
	, `email`)
VALUES ('2', 'lisi', '123456', '李四', '20'
	, 'test2@itcast.cn');

INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`
	, `email`)
VALUES ('3', 'wangwu', '123456', '王五', '28'
	, 'test3@itcast.cn');

INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`
	, `email`)
VALUES ('4', 'zhaoliu', '123456', '赵六', '21'
	, 'test4@itcast.cn');

INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`
	, `email`)
VALUES ('5', 'sunqi', '123456', '孙七', '24'
	, 'test5@itcast.cn');

Mybatis + MP

1)Mybatis实现查询User

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

<?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;allowMultiQuerie s=true&amp;useSSL=false" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers> <mapper resource="UserMapper.xml" /> </mappers>
</configuration>
第二步,编写User实体对象pojo:
@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接口:

public interface UserMapper {
  List<User> findAll();
}
第四步,编写UserMapper.xml文件:

<mapper namespace="cn.itcast.mp.simple.mapper.UserMapper">
  <select id="findAll" resultType="cn.itcast.mp.simple.pojo.User">
    select * from tb_user
  </select>
</mapper>
//第五步,编写TestMybatis测试用例:

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

2)Mybatis+MP实现查询User

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

public interface UserMapper extends BaseMapper<User> {
  List<User> findAll();
}
//第二步,使用MP中的MybatisSqlSessionFactoryBuilder进程构建:

public class TestMybatisPlus {
   
    @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);
        }
    }
}
运行报错:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E852Wfh3-1648380519212)(Pic/20210712091207.png)]

解决:在User对象中添加@TableName,指定数据库表名
image-20210706111317136
由于使用了MybatisSqlSessionFactoryBuilder进行了构建,继承的BaseMapper中的方法就载入到了SqlSession中,所以就可以直接使用相关的方法
image-20210706111531131

Spring + Mybatis + MP

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

1)实现查询User

第一步,编写jdbc.properties
第二步,编写applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="classpath:*.properties"/>
    <!-- 定义数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="maxActive" value="10"/>
        <property name="minIdle" value="5"/>
    </bean>
    <!--这里使用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>
</beans>
//第三步,编写User对象以及UserMapper接口:

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {
   
    private Long id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}
public interface UserMapper extends BaseMapper<User> {
   
}
//第四步,编写测试用例:

@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,所以需要重新创建工程,并不是创建子Module。

1)编写application.properties

2)编写pojo

3)编写mapper

4)编写启动类

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

5)编写测试用例

通用CRUD

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

插入操作

1)方法定义

/** * 插入一条记录 * * @param entity 实体对象 */
int insert(T entity);

2)测试用例

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
   
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testInsert(){
   
        User user = new User();
        user.setAge(20);
        user.setEmail("test@itcast.cn");
        user.setName("曹操");
        user.setUserName("caocao");
        user.setPassword("123456");
        int result = this.userMapper.insert(user); //返回的result是受影响的行数,并不是自增后的id
            System.out.println("result = " + result);
        System.out.println(user.getId()); //自增后的id会回填到对象中
    }
}
//如何设置id的生成策略呢?
//MP支持的id策略:
package com.baomidou.mybatisplus.annotation;
import lombok.Getter;
/** * 生成ID类型枚举类 */
@Getter
public enum IdType {
   

    /** * 数据库ID自增 */
    AUTO(0),
    
    /** * 该类型为未设置主键类型 */
    NONE(1),
    
    /** * 用户输入ID * <p>该类型可以通过自己注册自动填充插件进行填充</p> */
    INPUT(2),
    
    /* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */
    /** * 全局唯一ID (idWorker) */
    ID_WORKER(3),
    
    /** * 全局唯一ID (UUID) */
    UUID(4),
    
    /** * 字符串全局唯一ID (idWorker 的字符串表示) */
    ID_WORKER_STR(5);
    
    private final int key;
    
    IdType(int key) {
   
        this.key = key;
    }
}
修改User对象:
@TableId(type = IdType.AUTO) //指定id类型为自增长
private Long id;
@TableField
在MP中通过@TableField注解可以指定字段的一些属性,常常解决的问题有2个:
1、对象中的属性名和字段名不一致的问题(非驼峰)
2、对象中的属性字段在表中不存在的问题
使用:
image-20210706113814337

更新操作

在MP中,更新操作有2种,一种是根据id更新,另一种是根据条件更新。
根据条件更新

方法定义:
/** * 根据 whereEntity 条件,更新记录 * * @param entity 实体对象 (set 条件值,可以为 null) * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句) */
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T>
updateWrapper);
//测试用例:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
   
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testUpdate() {
   
        User user = new User();
        user.setAge(22); //更新的字段
        //更新的条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", 6);
        //执行更新操作
        int result = this.userMapper.update(user, wrapper);
        System.out.println("result = " + result);
    }
}
//或者,通过UpdateWrapper进行更新:

@Test
public void testUpdate() {
   
    //更新的条件以及字段
    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.eq("id", 6).set("age", 23);
    //执行更新操作
    int result = this.userMapper.update(null, wrapper);
    System.out.println("result = " + result);
}

删除操作

1)deleteByMap

/** * 根据 columnMap 条件,删除记录 * * @param columnMap 表字段 map 对象 */
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
//测试用例:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
   
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testDeleteByMap() {
   
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("age",20);
        columnMap.put("name","张三");
        //将columnMap中的元素设置为删除的条件,多个之间为and关系
        int result = this.userMapper.deleteByMap(columnMap);
        System.out.println("result = " + result);
    }
}

查询操作

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

SQL注入的原理

前面我们已经知道,MP在启动后会将BaseMapper中的一系列的方法注册到meppedStatements中,那么究竟是如
何注入的呢?流程又是怎么样的?
在MP中,ISqlInjector负责SQL的注入工作,它是一个接口,AbstractSqlInjector是它的实现类,实现关系如下:
image-20210706133710607
//在AbstractSqlInjector中,主要是由inspectInject()方法进行注入的,如下:

@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 method was found.");
            }
            mapperRegistryCache.add(className);
        }
    }
}
在实现方法中, methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass,tableInfo)); 是关键,循环遍历方法,进行注入。
最终调用抽象方法injectMappedStatement进行真正的注入:
/** * 注入自定义 MappedStatement * * @param mapperClass mapper 接口 * @param modelClass mapper 泛型 * @param tableInfo 数据库表反射信息 * @return MappedStatement */
public abstract MappedStatement injectMappedStatement(Class<?> mapperClass, Class<? > modelClass, TableInfo tableInfo);
查看该方法的实现:
image-20210706142501128
//以SelectById为例查看:

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方法添加到mappedStatements中。
image-20210706143612309

四、配置

4.1 基本配置

1、configLocation
MyBatis 配置文件位置,如果您有单独的 MyBatis 配置,请将其路径配置到 configLocation 中。
image-20210706144014275
2、mapperLocations
MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。
image-20210706144207461
3、typeAliasesPackage
MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。

image-20210706155426974

4.2 进阶配置

本部分(Configuration)的配置大都为 MyBatis 原生支持的配置,这意味着您可以通过 MyBatis XML 配置文件的形式进行配置。

1、mapUnderscoreToCamelCase
是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java 属性名 aColumn(驼峰命名) 的类似映射。
注意:
此属性在 MyBatis 中原默认值为 false,在 MyBatis-Plus 中,此属性也将用于生成最终的 SQL 的 select body,如果您的数据库命名符合规则无需使用 @TableField 注解指定数据库字段名

image-20210706160048994
2、cacheEnabled
全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为 true。

image-20210706160756593

4.3 DB 策略配置

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

image-20210706161011763
2、tablePrefix
表名前缀,全局配置后可省略@TableName()配置。

image-20210706161140745

五、条件构造器

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

image-20210706161355323

5.1 allEq

allEq(Map<R, V> params)
allEq(Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, Map<R, V> params, boolean null2IsNull)

个别参数说明: 
params : key 为数据库字段名, value 为字段值 
null2IsNull : 为true则在map的value为null时调用isNull方法,为false时则忽略value为null的
例1: allEq({id:1,name:"老王",age:null}) ---> id = 1 and name = '老王' and age is null
例2: allEq({id:1,name:"老王",age:null}, false) ---> id = 1 and name = '老王'
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)

个别参数说明: 
filter : 过滤函数,是否允许字段传入比对条件中 
params 与 null2IsNull : 同上
例1: allEq((k,v) -> k.indexOf("a") > 0, {id:1,name:"老王",age:null}) ---> name = '老王'
and age is null
例2: allEq((k,v) -> k.indexOf("a") > 0, {id:1,name:"老王",age:null}, false) ---> name =
'老王'

5.2 基本比较操作

eq
等于 =

ne
不等于 <>

gt
大于 >

ge
大于等于 >=

lt
小于 <

le
小于等于 <=

between
BETWEEN 值1 AND 值2

notBetween
NOT BETWEEN 值1 AND 值2

in
字段 IN (value.get(0), value.get(1), ...)

notIn
字段 NOT IN (v0, v1, ...)

5.3 模糊查询

like
LIKE '%值%'
例: like("name", "王") ---> name like '%王%'

notLike
NOT LIKE '%值%'
例: notLike("name", "王") ---> name not like '%王%'

likeLeft
LIKE '%值'
例: likeLeft("name", "王") ---> name like '%王'

likeRight
LIKE '值%'
例: likeRight("name", "王") ---> name like '王%'

5.4 排序

orderBy
排序:ORDER BY 字段, ...
例: orderBy(true, true, "id", "name") ---> order by id ASC,name ASC

orderByAsc
排序:ORDER BY 字段, ... ASC
例: orderByAsc("id", "name") ---> order by id ASC,name ASC

orderByDesc
排序:ORDER BY 字段, ... DESC
例: orderByDesc("id", "name") ---> order by id DESC,name DESC

5.5 逻辑查询

or
拼接 OR
主动调用 or 表示紧接着下一个方法不是用 and 连接!(不调用 or 则默认为使用 and 连接)

and
AND 嵌套
例: and(i -> i.eq("name", "李白").ne("status", "活着")) ---> and (name = '李白' and status
<> '活着')

5.6 select

在MP查询中,默认查询所有的字段,如果有需要也可以通过select方法进行指定字段。

//SELECT id,name,age FROM tb_user WHERE name = ? OR age = ?
wrapper.eq("name", "李四")
    .or()
    .eq("age", 24)
    .select("id", "name", "age");

六、ActiveRecord

6.1 什么是ActiveRecord

ActiveRecord也属于ORM(对象关系映射)层,由Rails最早提出,遵循标准的ORM模型:表映射到记录,记录映射到对象,字段映射到对象属性。配合遵循的命名和配置惯例,能够很大程度的快速实现模型的操作,而且简洁易懂。

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

6.2 AR初探

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

6.3 根据主键查询

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

6.4 其它

新增数据、更新操作、删除操作、根据条件查询

七、插件

7.1 插件机制

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语法构建的处理

//拦截器示例:

package cn.itcast.mp.plugins;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import java.util.Properties;
@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容器:

/**
* 自定义拦截器
*/
@Bean
public MyInterceptor myInterceptor(){
	return new MyInterceptor();
}
或者通过xml配置,mybatis-config.xml:

<configuration>
    <plugins>
        <plugin interceptor="cn.itcast.mp.plugins.MyInterceptor"></plugin>
    </plugins>
</configuration>

7.2 执行分析插件

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

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

当执行全表更新时,会抛出异常,这样有效防止了一些误操作。

7.3 性能分析插件

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

<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>

7.4 乐观锁插件

1、主要适用场景
意图:当要更新一条记录的时候,希望这条记录没有被别人更新

乐观锁实现方式:
取出记录时,获取当前version
更新时,带上这个version
执行更新时, set version = newVersion where version = oldVersion
如果version不对,就更新失败
2、插件配置

spring xml:
<bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>

spring boot:
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
	return new OptimisticLockerInterceptor();
}
3、注解实体字段
需要为实体字段添加@Version注解。

第一步,为表添加version字段,并且设置初始值为1:
ALTER TABLE `tb_user`
ADD COLUMN `version` int(10) NULL AFTER `email`;
UPDATE `tb_user` SET `version`='1';

第二步,为User实体对象添加version字段,并且添加@Version注解:
@Version
private Integer version;
//4、测试
@Test
public void testUpdate(){
   
    User user = new User();
    user.setAge(30);
    user.setId(2L);
    user.setVersion(1); //获取到version为1
    int result = this.userMapper.updateById(user);
    System.out.println("result = " + result);
}
可以看到,更新的条件中有version条件,并且更新的version为2。
如果再次执行,更新则不成功。这样就避免了多人同时更新时导致数据的不一致。
特别说明

支持的数据类型只有: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中的方法,又该如何实现呢?
下面我们以扩展findAll方法为例进行学习。

8.1 编写MyBaseMapper

package cn.itcast.mp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
public interface MyBaseMapper<T> extends BaseMapper<T> {
   
    List<T> findAll();
}
其他的Mapper都可以继承该Mapper,这样实现了统一的扩展。
package cn.itcast.mp.mapper;
import cn.itcast.mp.pojo.User;
public interface UserMapper extends MyBaseMapper<User> {
   
    User findById(Long id);
}

8.2 编写MySqlInjector

如果直接继承AbstractSqlInjector的话,原有的BaseMapper中的方法将失效,所以我们选择继承DefaultSqlInjector进行扩展。
package cn.itcast.mp.sqlInjector;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import java.util.List;
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;
    }
}

8.3 编写FindAll

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

8.4 注册到Spring容器

/**
* 自定义SQL注入器
*/
@Bean
public MySqlInjector mySqlInjector(){
	return new MySqlInjector();
}

8.5 测试

@Test
public void testFindAll(){
   
    List<User> users = this.userMapper.findAll();
    for (User user : users) {
   
        System.out.println(user);
    }
}

九、自动填充功能

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

9.1 添加@TableField注解

@TableField(fill = FieldFill.INSERT) //插入数据时进行填充
private String password;
为password添加自动填充功能,在新增数据时有效。
FieldFill提供了多种模式选择:

public enum FieldFill {
   
    /** * 默认不处理 */
    DEFAULT,
    /** * 插入时填充字段 */
    INSERT,
    /** * 更新时填充字段 */
    UPDATE,
    /** * 插入和更新时填充字段 */
    INSERT_UPDATE
}

9.2 编写MyMetaObjectHandler

@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) {
   
    }
}

9.3 测试

@Test
public void testInsert(){
   
    User user = new User();
    user.setName("关羽");
    user.setUserName("guanyu");
    user.setAge(30);
    user.setEmail("guanyu@itast.cn");
    user.setVersion(1);
    int result = this.userMapper.insert(user);
    System.out.println("result = " + result);
}

十、逻辑删除

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

10.1 修改表结构

为tb_user表增加deleted字段,用于表示数据是否被删除,1代表删除,0代表未删除。
ALTER TABLE `tb_user`
ADD COLUMN `deleted` int(1) NULL DEFAULT 0 COMMENT '1代表删除,0代表未删除' AFTER
`version`;

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

10.2 配置

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

10.3 测试

@Test
public void testDeleteById(){
	this.userMapper.deleteById(2L);
}

十一、通用枚举

11.1 修改表结构

ALTER TABLE `tb_user`
ADD COLUMN `sex` int(1) NULL DEFAULT 1 COMMENT '1-男,2-女' AFTER `deleted`;

11.2 定义枚举

public enum SexEnum implements IEnum<Integer> {
   
    MAN(1,"男"),
    WOMAN(2,"女");
    private int value;
    private String desc;
    SexEnum(int value, String desc) {
   
        this.value = value;
        this.desc = desc;
    }
    @Override
    public Integer getValue() {
   
        return this.value;
    }
    @Override
    public String toString() {
   
        return this.desc;
    }
}

11.3 配置

# 枚举包扫描
mybatis-plus.type-enums-package=cn.itcast.mp.enums

11.4 修改实体

private SexEnum sex;

11.5 测试

@Test
public void testInsert(){
   
    User user = new User();
    user.setName("貂蝉");
    user.setUserName("diaochan");
    user.setAge(20);
    user.setEmail("diaochan@itast.cn");
    user.setVersion(1);
    user.setSex(SexEnum.WOMAN);
    int result = this.userMapper.insert(user);
    System.out.println("result = " + result);
}

十二、代码生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、MapperXML、Service、Controller 等各个模块的代码,极大的提升了开发效率。