package com.ssc.mp.plugins;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import java.util.Properties;
/**
* @ClassName MyInterceptor
* @Description TODO
* @Authoc 孙少聪
* @Date 2022/6/30 19:42:59
*/
@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) {
//属性设置
}
}
有拦截的方法是update
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
会执行四次plugin是因为可以拦截的点有四个阶段。
防止一些误操作
@Configuration
@MapperScan("com.ssc.mp.mapper") //设置mapper接口的扫描包
public class MybatisPlusConfig {
/**
* SQL分析插件
*/
@Bean
public SqlExplainInterceptor sqlExplainInterceptor(){
SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor();
List<ISqlParser> list = new ArrayList<>();
list.add(new BlockAttackSqlParser()); // 全表更新或者删除的组短期
sqlExplainInterceptor.setSqlParserList(list);
return sqlExplainInterceptor;
}
}
@Test
public void testUpadateAll(){
User user = new User();
user.setName("刘备"); // 更新数据
boolean result = user.update(null); //全表更新
System.out.println(result);
}
<plugins>
<!--性能分析插件-->
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor">
<!--最大执行时间,单位为毫秒-->
<property name="maxTime" value="1000"/>
<!--输出的sql坐格式化,默认为false-->
<property name="format" value="true"/>
</plugin>
</plugins>
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"></plugin>
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
// 乐观锁的版本字段
@Version
private Integer version;
@Test
public void testUpdateVersion(){
User user = new User();
user.setId(2L); // 更新数据
user.setAge(31);
user.setVersion(1); // 当前版本信息
boolean result = user.updateById();
System.out.println(result);
}
Execute SQL:
UPDATE
tb_user
SET
age=31,
version=2
WHERE
id=2
AND version=1
int
,Integer
,long
,Long
,Date
,Timestamp
,LocalDateTime
仅支持 updateById(id) 与 update(entity, wrapper) 方法