插件机制
- MyBatis允许你在已映射语句执行过程中的某一点进行拦截调用。 默认情况下, MyBatis允许使用插件来拦截的方法调用包括
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
-
总体概括为
-
拦截执行器的方法
拦截参数的处理
拦截结果的处理
拦截Sql语法构建的处理
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;
@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) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
会执行四次plugin是因为可以拦截的点有四个阶段。
执行分析插件
- 在Mybatis-Plus中提供了SQL执行的分析的插件,可作用于全表的更新,删除的操作。注意:该插件仅适用于开发环境不适用于生产环境
防止一些误操作
@Configuration
@MapperScan("com.ssc.mp.mapper")
public class MybatisPlusConfig {
@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"/>
<property name="format" value="true"/>
</plugin>
</plugins>
乐观锁插件
适用
- 当更新一条记录时,希望这条记录没有被别人更新
-
乐观锁实现方式
-
去除记录时,获取当前version
更新时,带上这个version
执行更新时,set version = newVersion where version = oldVersion
如果version不对,就更新失败
插件配置
<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
- 整数类型下 newVersion = oldVersion + 1
- newVersion 会回写到 entity 中
仅支持 updateById(id) 与 update(entity, wrapper) 方法
- 在 update(entity, wrapper) 方法下, wrapper不能和其他逻辑复用