这篇文章主要介绍"如何使用mybatis的拦截机修改执行结构化查询语言和传入参数",在日常操作中,相信很多人在如何使用mybatis的拦截机修改执行结构化查询语言和传入参数问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"如何使用mybatis的拦截机修改执行结构化查询语言和传入参数"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
mybatis interceptor修改执行sql以及传入参数
项目中途遇到业务需求更改,在查询某张表时需要增加条件,由于涉及的结构化查询语言语句多而且依赖其他服务的罐子,逐个修改结构化查询语言语句和接口太繁杂。项目使用mybatis框架,因此借鉴页面助手插件尝试使用mybatis的拦截机来实现改需求。
总体思路
从BoundSql中获取sql,通过正则匹配替换表名为子查询REPLACE_TXT
添加子查询REPLACE_TXT中需要用到的参数到mybatis参数列表中
添加参数与占位符映射,即添加参数映射对象到参数映射中,由于声明在执行时是按照参数映射的元素索引定位占位符封装参数(即参数映射中的第一个参数会封装到第一个占位符上),因此参数映射中的参数顺序需要和占位符保持一致。其次参数映射的元素个数需要和占位符个数保持一致。
为了保证该拦截在最后执行,使用自动配置将拦截添加到SqlSessionFactory的配置中,并在春天。工厂文件中添加自动配置
未测试性能以及是否存在未知缺陷
1、Interceptor 代码实现
包组织。cnbi。项目。其他。SQL。拦截;
进口cn。胡工具。核心。乌提尔。Numberutil
导入com。cnbi。云。常见。核心。例外。服务异常;
导入com。github。页面助手。页面;
导入com。github。页面助手。乌提尔。Executurutil
导入com。github。页面助手。乌提尔。MetaObjectutil
导入组织。阿帕奇。伊巴蒂斯。建筑商。注释。providersqlsource
导入组织。阿帕奇。伊巴蒂斯。缓存。cachekey
导入组织。阿帕奇。伊巴蒂斯。执行者。遗嘱执行人;
导入组织。阿帕奇。伊巴蒂斯。映射。Boundsql
导入组织。阿帕奇。伊巴蒂斯。映射。mappedstatement
导入组织。阿帕奇。伊巴蒂斯。映射。参数映射;
导入组织。阿帕奇。伊巴蒂斯。插件。*;
导入组织。阿帕奇。伊巴蒂斯。反思。MetaObject
导入组织。阿帕奇。伊巴蒂斯。会话。resulthandler
导入组织。阿帕奇。伊巴蒂斯。会话。RoWbounds
导入组织。cnbi。项目。其他。SQL。AOP。期间持有人;
导入Java。乌提尔。*;
导入Java。乌提尔。regex。火柴人;
导入Java。乌提尔。regex。模式;
/**
* @类名参数拦截器
* @描述修改接口太繁琐,直接用mybatis拦截器对查询结构化查询语言进行拦截,将期间参数注入结构化查询语言
*@AuthorWangjunkai
* @日期2019/10/2311:36
**/
@截获({ 0
@签名(类型=Executor.class,符合
hod = "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<Integer> paramIndex = new ArrayList<>();
while(matcher.find(index)){
index = matcher.end();
String sqlPart = sql.substring(0, index);
int slot = index - sqlPart.replace("?", "").length() + paramIndex.size() ;
paramIndex.add(slot);
paramIndex.add(slot + 1);
}
//替换子查询
String companyPeriodSql = matcher.replaceAll(REPLACE_TXT);
cacheKey = args.length == 4 ? executor.createCacheKey(ms, parameter, rowBounds, boundSql) : (CacheKey) args[4];
//处理参数
Object parameterObject = processParameterObject(ms, parameter, boundSql, cacheKey, paramIndex);
BoundSql companyPeriodBoundSql = new BoundSql(ms.getConfiguration(), companyPeriodSql, boundSql.getParameterMappings(), parameterObject);
Map<String, Object> additionalParameters = ExecutorUtil.getAdditionalParameter(boundSql);
//设置动态参数
for (String key : additionalParameters.keySet()) {
companyPeriodBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
return executor.query(ms, parameterObject, RowBounds.DEFAULT, resultHandler, cacheKey, companyPeriodBoundSql);
}
public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey, ArrayList<Integer> paramIndex) {
//处理参数
Map<String, Object> paramMap = null;
if (parameterObject == null) {
paramMap = new HashMap<>();
} else if (parameterObject instanceof Map) {
//解决不可变Map的情况
paramMap = new HashMap<>();
paramMap.putAll((Map) parameterObject);
} else {
paramMap = new HashMap<>();
// sqlSource为ProviderSqlSource时,处理只有1个参数的情况
if (ms.getSqlSource() instanceof ProviderSqlSource) {
String[] providerMethodArgumentNames = ExecutorUtil.getProviderMethodArgumentNames((ProviderSqlSource) ms.getSqlSource());
if (providerMethodArgumentNames != null && providerMethodArgumentNames.length == 1) {
paramMap.put(providerMethodArgumentNames[0], parameterObject);
paramMap.put("param1", parameterObject);
}
}
//动态sql时的判断条件不会出现在ParameterMapping中,但是必须有,所以这里需要收集所有的getter属性
//TypeHandlerRegistry可以直接处理的会作为一个直接使用的对象进行处理
boolean hasTypeHandler = ms.getConfiguration().getTypeHandlerRegistry().hasTypeHandler(parameterObject.getClass());
MetaObject metaObject = MetaObjectUtil.forObject(parameterObject);
//需要针对注解形式的MyProviderSqlSource保存原值
if (!hasTypeHandler) {
for (String name : metaObject.getGetterNames()) {
paramMap.put(name, metaObject.getValue(name));
}
}
//下面这段方法,主要解决一个常见类型的参数时的问题
if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) {
for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
String name = parameterMapping.getProperty();
if (!name.equals(GLOBALPERIOD)
&& paramMap.get(name) == null) {
if (hasTypeHandler
|| parameterMapping.getJavaType().equals(parameterObject.getClass())) {
paramMap.put(name, parameterObject);
break;
}
}
}
}
}
return processPageParameter(ms, paramMap, boundSql, pageKey, paramIndex);
}
private final static String GLOBALPERIOD = "globalPeriod";
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, BoundSql boundSql, CacheKey pageKey, ArrayList<Integer> paramIndex) {
paramMap.put(GLOBALPERIOD, getPeriod());
//处理pageKey
pageKey.update(getPeriod());
//处理参数配置
handleParameter(boundSql, ms, paramIndex);
return paramMap;
}
protected void handleParameter(BoundSql boundSql, MappedStatement ms, ArrayList<Integer> paramIndex) {
if (boundSql.getParameterMappings() != null) {
List<ParameterMapping> newParameterMappings = new ArrayList<>(boundSql.getParameterMappings());
for (Integer index : paramIndex) {
if(index < newParameterMappings.size()) {
newParameterMappings.add(index, new ParameterMapping.Builder(ms.getConfiguration(), GLOBALPERIOD, String.class).build());
}else{
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), GLOBALPERIOD, String.class).build());
}
}
MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
metaObject.setValue("parameterMappings", newParameterMappings);
}
}
private final static String Q = "Q";
private final static String H = "H";
private String getPeriod(){
//使用threadlocal保存从request中获取的参数,此处不再描述
String period = PeriodHolder.getPeriod();
if(NumberUtil.isNumber(period)){
return period;
}else if(period.contains(Q)){
return period.substring(0, 4) + Integer.parseInt(period.substring(5)) * 3;
}else if(period.contains(H)){
return period.substring(0, 4) + Integer.parseInt(period.substring(5)) * 6;
}else{
throw new ServiceException("非法期间:" + period);
}
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
//nothing to do...
}
}
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<SqlSessionFactory> sqlSessionFactoryList; public ParamIntecepterAutoConfiguration() { } @PostConstruct public void addParamInterceptor() { ParamInterceptor interceptor = new ParamInterceptor(); Iterator var3 = this.sqlSessionFactoryList.iterator(); while(var3.hasNext()) { SqlSessionFactory sqlSessionFactory = (SqlSessionFactory)var3.next(); sqlSessionFactory.getConfiguration().addInterceptor(interceptor); } } }
mybatis interceptor 处理查询参数及查询结果
拦截器:拦截update,query方法
处理查询参数及返回结果。
/** * Created by windwant on 2017/1/12. */ @Intercepts({ @Signature(type=Executor.class,method="update",args={MappedStatement.class,Object.class}), @Signature(type=Executor.class,method="query",args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class}) }) public class EncryptInterceptor implements Interceptor { public static final Logger logger = LoggerFactory.getLogger(EncryptInterceptor.class); @Override public Object intercept(Invocation invocation) throws Throwable { dealParameter(invocation); Object returnValue = invocation.proceed(); dealReturnValue(returnValue); return returnValue; } //查询参数加密处理 private void dealParameter(Invocation invocation) { MappedStatement statement = (MappedStatement) invocation.getArgs()[0]; String mapperl = ConfigUtils.get("mybaits.mapper.path"); String methodName = statement.getId().substring(statement.getId().indexOf(mapperl) + mapperl.length() + 1); if (methodName.startsWith("UserBaseMapper")){ if(methodName.equals("UserBaseMapper.updateDriver")){ ((Driver) invocation.getArgs()[1]).encrypt(); } } logger.info("Mybatis Encrypt parameters Interceptor, method: {}, args: {}", methodName, invocation.getArgs()[1]); } //查询结果解密处理 private void dealReturnValue(Object returnValue){ if(returnValue instanceof ArrayList<?>){ List<?> list = (ArrayList<?>)returnValue; for(Object val: list){ if(val instanceof Passenger){/// //TODO } logger.info("Mybatis Decrypt result Interceptor, result object: {}", ToStringBuilder.reflectionToString(val)); } } } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } }
添加xml配置
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="typeAliasesPackage" value="com.xx.model"/> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath*:mybatis/*.xml"></property> <property name="plugins">//拦截器插件 <array> <bean class="com.github.pagehelper.PageHelper"> <property name="properties"> <value>dialect=hsqldb</value> </property> </bean> <bean class="com.xx.interceptor.EncryptInterceptor"> <property name="properties"> <value>property-key=property-value</value> </property> </bean> </array> </property> </bean>
到此,关于“如何使用mybatis的interceptor修改执行sql和传入参数”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!
内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/133164.html