Mybatis-Plus学习笔记(一)

Mybatis-Plus

Mybatis-Plus概念

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

Mybatis-Plus介绍

https://mp.baomidou.com/https://mp.baomidou.com/

特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

架构

在这里插入图片描述

作者

Mybatis-Plus是由baomidou(苞米豆)组织开发并且开源的,目前该组织大概有30人左右。码云地址

Mybatis-Plus快速入门

Maven依赖坐标

<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.4.0</version>
</dependency>

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

编写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>
<properties resource="jdbc.properties"></properties>
<!--environments: 运行环境-->
	<environments default="development">
		<environment id="development">
			<!--当前的事务事务管理器是JDBC-->
			<transactionManager type="JDBC"></transactionManager>
			<!--数据源信息 POOLED:使用mybatis的连接池-->
			<dataSource type="POOLED">
			<property name="driver" value="${jdbc.driver}"/>
			<property name="url" value="${jdbc.url}"/>
			<property name="username" value="${jdbc.username}"/>
			<property name="password" value="${jdbc.password}"/>
			</dataSource>
		</environment>
	</environments>
	<!--引入映射配置文件-->
	<mappers>
		<mapper resource="mapper/UserMapper.xml"></mapper>
	</mappers>
</configuration>

实体对象:(这里使用lombok进行了进化bean操作)

@Data // getter setter @toString
@NoArgsConstructor
@AllArgsConstructor
public class User {
	private Long id;
	private String name;
	private Integer age;
	private String email;
}

Mybatis+MP实现查询User

第一步,将UserMapper继承BaseMapper,将拥有了BaseMapper中的所有方法:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lagou.pojo.User;
public interface UserMapper extends BaseMapper<User> {
}
第二步,使用MP中的MybatisSqlSessionFactoryBuilder进程构建:
@Test
public void test2() throws IOException {
	InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
	//这里使用的是MP中的MybatisSqlSessionFactoryBuilder
	SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(resourceAsStream);
	SqlSession sqlSession = sqlSessionFactory.openSession();
	UserMapper mapper = sqlSession.getMapper(UserMapper.class);
	// 可以调用BaseMapper中定义的方法
	List<User> all = mapper.selectList(null);
	for (User user : all) {
		System.out.println(user);
	}
}

注:如果实体类名称和表名称不一致,可以在实体类上添加注解@TableName(“指定数据库表名”)

Spring + Mybatis + MP

引入了Spring框架,数据源、构建等工作就交给了Spring管理。
主要是在applicationContext.xml中添加MP的MybatisSqlSessionFactoryBean

<!--这里使用MP提供的sqlSessionFactory,完成spring与mp的整合-->
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>

SpringBoot + Mybatis + MP

编写application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?
useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
编写mapper
public interface UserMapper extends BaseMapper<User> {
}
编写测试方法
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@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、对象中的属性名和字段名不一致的问题(非驼峰)
2、对象中的属性字段在表中不存在的问题

使用

在这里插入图片描述

其他用法,如大字段不加入查询字段:

在这里插入图片描述

更新

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

根据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);
通过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);
}

删除操作

deleteById
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
import org.springframework.test.context.junit4.SpringRunner;
	@RunWith(SpringRunner.class)
	@SpringBootTest
	public class UserMapperTest {
	@Autowired
	private UserMapper userMapper;
	@Test
	public void testDeleteById() {
		//执行删除操作
		int result = this.userMapper.deleteById(6L);
		System.out.println("result = " + result);
	}
}
deleteByMap
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
delete
/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
批量删除deleteBatchIds
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends
Serializable> idList);

查询操作

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

selectById根据主键查询
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends
Serializable> idList);
selectBatchIds根据Id批量查询
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends
Serializable> idList);
selectOne
/**
* 根据 entity 条件,查询一条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
selectCount
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
selectList
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
selectPage
/**
* 根据 entity 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
IPage<T> selectPag

SQL注入的原理

MP在启动后会将BaseMapper中的一系列的方法注册到meppedStatements中,在MP中,ISqlInjector负责SQL的注入工作,它是一个接口,AbstractSqlInjector是它的实现类,实现关
系如下:
在这里插入图片描述
在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);
该方法的实现:

在这里插入图片描述
以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方法添加到meppedStatements中。

配置

在MP中有大量的配置,其中一部分是Mybatis原生配置,另一部分是MP的配置详情

基本配置

configLocation

MyBatis 配置文件位置,如果有单独的 MyBatis 配置,请将其路径配置到 configLocation 中。MyBatisConfiguration 的具体内容请参考MyBatis 官方文档
Spring Boot:

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

Spring MVC:

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

MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。
Spring Boot:

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

Spring MVC:

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

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

typeAliasesPackage

MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。
Spring Boot:

mybatis-plus.type-aliases-package = com.lagou.mp.pojo

Spring MVC:

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

进阶配置

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

mapUnderscoreToCamelCase

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

#关闭自动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
mybatis-plus.configuration.map-underscore-to-camel-case=false
cacheEnabled

类型: boolean ** 默认值**: true
全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为 true。
示例(SpringBoot):

mybatis-plus.configuration.cache-enabled=false

DB 策略配置

idType

类型: com.baomidou.mybatisplus.annotation.IdType 默认值: ID_WORKER
全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置。
SpringBoot:

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

Spring MVC:

<!--这里使用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:

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

SpringMVC:

<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接口的实现类关系如下:
在这里插入图片描述
可以看到,AbstractWrapper和AbstractChainWrapper是重点实现,接下来我们重点学习
AbstractWrapper以及其子类。
说明:
QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类
用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件
注意: entity 生成的 where 条件与 使用各个 api 生成的 where 条件没有任何关联行为
官网文档地址:https://mybatis.plus/guide/wrapper.html

allEq

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

全部eq(或个别isNull)
个别参数说明

  • 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 = ‘老王’

基本比较操作

在这里插入图片描述

模糊查询

在这里插入图片描述

排序

在这里插入图片描述

逻辑查询

在这里插入图片描述

select

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

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

ActiveRecord

ActiveRecord(简称AR)一直广受动态语言( PHP 、 Ruby 等)的喜爱,而 Java 作为准静态语言,对于 ActiveRecord 往往只能感叹其优雅,所以我们也在 AR 道路上进行了一定的探索,喜欢大家能够喜欢。
ActiveRecord也属于ORM(对象关系映射)层,由Rails最早提出,遵循标准的ORM模型:表映射到记录,记录映射到对象,字段映射到对象属性。配合遵循的命名和配置惯例,能够很大程度的快速实现模型的操作,而且简洁易懂。
ActiveRecord的主要思想是:

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

开启AR之旅

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

package com.lagou.mp.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User extends Model<User> {
	private Long id;
	private String userName;
	private String password;
	private String name;
	private Integer age;
	private String email;
}

根据主键查询

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

新增数据

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
	@Autowired
	private UserMapper userMapper;
	@Test
	public void testARInsert() {
		User user = new User();
		user.setName("应颠");
		user.setAge(30);
		user.setEmail("liubei@lagou.cn");
		boolean insert = user.insert();
		System.out.println(insert);
	}
}

更新操作

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
	@Autowired
	private UserMapper userMapper;
	@Test
	public void testAR() {
		User user = new User();
		user.setId(8L);
		user.setAge(35);
		boolean update = user.updateById();
		System.out.println(update);
	}
}

删除操作

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
	@Autowired
	private UserMapper userMapper;
	@Test
	public void testAR() {
		User user = new User();
		user.setId(7L);
		boolean delete = user.deleteById();
		System.out.println(delete);
	}
}

根据条件查询

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
	@Autowired
	private UserMapper userMapper;
	@Test
	public void testARFindById() {
		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);
		}
	}
}

插件

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等方法,还有其他接口的一些方法等。总体概括为:
  5. 拦截执行器的方法
  6. 拦截参数的处理
  7. 拦截结果集的处理
  8. 拦截Sql语法构建的处理
    拦截器示例:
package com.lagou.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:

<?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>
<plugins>
<plugin interceptor="com.lagou.mp.plugins.MyInterceptor"></plugin>
</plugins>
</configuration>

执行分析插件

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

性能分析插件

性能分析拦截器,用于输出每条 SQL 语句及其执行时间,可以设置最大执行时间,超过时间会抛出异常。该插件只用于开发环境,不建议在生产环境使用
配置
javaconfig方式

@Bean
public PerformanceInterceptor performanceInterceptor(){
	PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
	performanceInterceptor.setMaxTime(100);
	performanceInterceptor.setFormat(true);
	return performanceInterceptor;
}

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>
<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>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值