拦截器的基本使用,本文不涉及,请看此篇文章介绍。
定义SQL语句拦截器
查询SQL语句拦截器
/**
* [ mybaits sql 拦截器 ]
*
* @author be_insighted
*/
@Intercepts({@Signature(type = org.apache.ibatis.executor.Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
@Slf4j
public class MyBatisSqlQuerySqlDebugPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = invocation.getArgs()[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
log.info("=====> SQL日志查询:\n" + boundSql.getSql() + "\r\n" + boundSql.getParameterMappings().toString());
Object obj = invocation.proceed();
return obj;
}
@Override
public Object plugin(Object arg0) {
return Plugin.wrap(arg0, this);
}
@Override
public void setProperties(Properties arg0) {
}
}
更新类SQL语句拦截器
@Intercepts({@Signature(type = org.apache.ibatis.executor.Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@Slf4j
public class MyBatisSqlUpdateSqlDebugPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = invocation.getArgs()[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
log.info("=====> SQL日志Update操作:\n " + boundSql.getSql() + "\r\n" + boundSql.getParameterMappings().toString());
Object obj = invocation.proceed();
return obj;
}
@Override
public Object plugin(Object arg0) {
return Plugin.wrap(arg0, this);
}
@Override
public void setProperties(Properties arg0) {
}
在配置类中将拦截器纳入到Spring容器
@EnableTransactionManagement
@Configuration
@MapperScan(basePackages = {"com.iot.**.*.dao"})
public class IotMybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
// left join的分页记录数不放大才能使用此优化 不然需要手工关闭优化配置 暂时无须此优化 先统一关闭了
// 开启 count 的 join 优化,只针对 left join !!!
// return new PaginationInterceptor().setCountSqlParser(new JsqlParserCountOptimize(true));
return new PaginationInterceptor();
}
/**
* 打印sql log
*
* @return
*/
@Bean
@Profile("dev")
ConfigurationCustomizer mybatisConfigurationCustomizer() {
return configuration -> {
configuration.addInterceptor(new MyBatisSqlUpdateSqlDebugPlugin());
configuration.addInterceptor(new MyBatisSqlQuerySqlDebugPlugin());
};
}
}
以上便是拦截器的使用,打印日志,以及@Profile注解的应用。