目录Mybatis Interceptor接口的使用测试中使用的config文件内容如下在配置文件中配置了一个Interceptor的实现类Interceptor修改执行sql及传入参数总体思路1、Interceptor 代码实现
2、AutoConfiguration代码实现
Mybatis Interceptor接口的使用关于Mybatis中插件的声明需要在configuration的配置文件中进行配置,配置文件的位置使用configLocation属性指定。
测试中使用的config文件内容如下在配置文件中配置了一个Interceptor的实现类LogInterceptor的代码如下:public class LogInterceptor implements Interceptor{@Override public Object intercept(Invocation invocation) throws Throwable {System.out.println("LogInterceptor : intercept");return null;}@Override public Object plugin(Object target) {if(target instanceof StatementHandler){RoutingStatementHandler handler = (RoutingStatementHandler)target;//打印出当前执行的sql语句System.out.println(handler.getBoundSql().getSql());}return target;}@Override public void setProperties(Properties properties) {System.out.println("LogInterceptor : setProperties");}}在工程的配置文件中,在配置SqlSessionFactoryBean时需要指明config配置文件的位置,配置文件如下:基本上这样配置以后,在工程中声明的plugin就已经生效了,实际中打印出来的log如下:SELECT * FROM city WHERE ID=?执行的CityMapper如下:简单的测试了一下,可以打印出sql语句。在使用mybatis提供的plugin接口时需要注意,在构建ParameterHandler 、ResultSetHandler 、StatementHandler 和Executor 的时候都会调用在项目中实现的插件接口,一般情况下,如果只是为了打印显示当前执行的sql语句,可以只在当target为StatementHandler类型的时候再进行处理即可。
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);return parameterHandler;}public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,ResultHandler resultHandler, BoundSql boundSql) {ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);return resultSetHandler;}public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {System.out.println("newStatementHandler......");StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);return statementHandler;}public Executor newExecutor(Transaction transaction) {return newExecutor(transaction, defaultExecutorType);}public Executor newExecutor(Transaction transaction, ExecutorType executorType) {executorType = executorType == null ? defaultExecutorType : executorType;executorType = executorType == null ? ExecutorType.SIMPLE : executorType;Executor executor;if (ExecutorType.BATCH == executorType) {executor = new BatchExecutor(this, transaction);} else if (ExecutorType.REUSE == executorType) {executor = new ReuseExecutor(this, transaction);} else {executor = new SimpleExecutor(this, transaction);}if (cacheEnabled) {executor = new CachingExecutor(executor);}executor = (Executor) interceptorChain.pluginAll(executor);return executor;}在实际测操作中,在项目中定义实现的plugin都会被添加保存到interceptorChain对象的一个集合中,在内部会对集合里的对象进行遍历,分别调用每个插件的plugin方法。
其中target就是在调用pluginAll传入的具体对象。。。
Interceptor修改执行sql及传入参数项目中途遇到业务需求更改,在查询某张表时需要增加条件,由于涉及的sql语句多而且依赖其他服务的jar,逐个修改sql语句和接口太繁杂。项目使用mybatis框架,因此借鉴PageHelper插件尝试使用mybatis的Interceptor来实现改需求。
总体思路从BoundSql中获取sql,通过正则匹配替换表名为子查询REPLACE_TXT添加子查询REPLACE_TXT 中需要用到的参数到mybatis参数列表中添加参数与占位符映射,即添加ParameterMapping对象到ParameterMappings中,由于statement在执行时是按照ParameterMappings的元素索引定位占位符封装参数(即ParameterMappings中的第一个参数会封装到第一个占位符上),因此ParameterMappings中的参数顺序需要和占位符保持一致。其次ParameterMappings的元素个数需要和占位符个数保持一致。
为了保证该intercept在最后执行,使用AutoConfiguration将intercept添加到SqlSessionFactory的Configuration中,并在spring.factories文件中添加AutoConfiguration未测试性能以及是否存在未知缺陷1、Interceptor 代码实现package org.cnbi.project.other.sql.intercept;import cn.hutool.core.util.NumberUtil;import com.cnbi.cloud.common.core.exception.ServiceException;import com.github.pagehelper.Page;import com.github.pagehelper.util.ExecutorUtil;import com.github.pagehelper.util.MetaObjectUtil;import org.apache.ibatis.builder.annotation.ProviderSqlSource;import org.apache.ibatis.cache.CacheKey;import org.apache.ibatis.executor.Executor;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.mapping.ParameterMapping;import org.apache.ibatis.plugin.*;import org.apache.ibatis.reflection.MetaObject;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import org.cnbi.project.other.sql.aop.PeriodHolder;import java.util.*;import java.util.regex.Matcher;import java.util.regex.Pattern;/*** @ClassName ParamInterceptor* @Description 修改接口太繁琐,直接用mybatis拦截器对查询sql进行拦截,将期间参数注入sql* @Author Wangjunkai* @Date 2019/10/23 11:36**/@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})}) public class ParamInterceptor implements Interceptor {private final static Pattern DW_DIMCOMPANY = Pattern.compile("dw_dimcompany", Pattern.CASE_INSENSITIVE);private final static String REPLACE_TXT = "(select * from dw_dimcompany where cisdel = '0' and START_PERIOD <= ? and END_PERIOD > ?)";@Override public Object intercept(Invocation invocation) throws Throwable {Object[] args = invocation.getArgs();MappedStatement ms = (MappedStatement) args[0];Object parameter = args[1];RowBounds rowBounds = (RowBounds) args[2];ResultHandler resultHandler = (ResultHandler) args[3];Executor executor = (Executor) invocation.getTarget();CacheKey cacheKey;BoundSql boundSql;if(args.length == 4){boundSql = ms.getBoundSql(parameter);} else {boundSql = (BoundSql) args[5];}//获取sql语句,使用正则忽略大小写匹配String sql = boundSql.getSql();Matcher matcher = DW_DIMCOMPANY.matcher(sql);//没有需要替换的表名则放行if(!matcher.find()){return invocation.proceed();}//收集占位符个数(即paramIndex 的size)以及占位符次序(slot:即参数在ParameterMappings中的顺序)
int index = 0;ArrayList
}}
2、AutoConfiguration代码实现
package org.cnbi.project.autoconfig;import com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration;import org.apache.ibatis.session.SqlSessionFactory;import org.cnbi.project.other.sql.intercept.ParamInterceptor;import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.AutoConfigureAfter;import org.springframework.context.annotation.Configuration;import javax.annotation.PostConstruct;import java.util.Iterator;import java.util.List;/*** @ClassName ParamIntecepterAutoConfiguration* @Description* @Author Wangjunkai* @Date 2019/10/23 15:41**/@AutoConfigureAfter({MybatisAutoConfiguration.class, PageHelperAutoConfiguration.class})@Configuration public class ParamIntecepterAutoConfiguration {@Autowired private List以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:Mybatis Interceptor 拦截器的实现mybatis interceptor 处理查询参数及查询结果的实例代码mybatis 自定义实现拦截器插件Interceptor示例基于MyBatis的简单使用(推荐)
