使用mybatis的interceptor修改執(zhí)行sql以及傳入?yún)?shù)方式
mybatis interceptor修改執(zhí)行sql以及傳入?yún)?shù)
項(xiàng)目中途遇到業(yè)務(wù)需求更改,在查詢某張表時(shí)需要增加條件,由于涉及的sql語(yǔ)句多而且依賴其他服務(wù)的jar,逐個(gè)修改sql語(yǔ)句和接口太繁雜。項(xiàng)目使用mybatis框架,因此借鑒PageHelper插件嘗試使用mybatis的Interceptor來(lái)實(shí)現(xiàn)改需求。
總體思路
- 從BoundSql中獲取sql,通過(guò)正則匹配替換表名為子查詢REPLACE_TXT
- 添加子查詢REPLACE_TXT 中需要用到的參數(shù)到mybatis參數(shù)列表中
- 添加參數(shù)與占位符映射,即添加ParameterMapping對(duì)象到ParameterMappings中,由于statement在執(zhí)行時(shí)是按照ParameterMappings的元素索引定位占位符封裝參數(shù)(即ParameterMappings中的第一個(gè)參數(shù)會(huì)封裝到第一個(gè)占位符上),因此ParameterMappings中的參數(shù)順序需要和占位符保持一致。其次ParameterMappings的元素個(gè)數(shù)需要和占位符個(gè)數(shù)保持一致。
- 為了保證該intercept在最后執(zhí)行,使用AutoConfiguration將intercept添加到SqlSessionFactory的Configuration中,并在spring.factories文件中添加AutoConfiguration
- 未測(cè)試性能以及是否存在未知缺陷
1、Interceptor 代碼實(shí)現(xiàn)
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攔截器對(duì)查詢sql進(jìn)行攔截,將期間參數(shù)注入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語(yǔ)句,使用正則忽略大小寫匹配
String sql = boundSql.getSql();
Matcher matcher = DW_DIMCOMPANY.matcher(sql);
//沒有需要替換的表名則放行
if(!matcher.find()){
return invocation.proceed();
}
//收集占位符個(gè)數(shù)(即paramIndex 的size)以及占位符次序(slot:即參數(shù)在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];
//處理參數(shù)
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);
//設(shè)置動(dòng)態(tài)參數(shù)
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) {
//處理參數(shù)
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時(shí),處理只有1個(gè)參數(shù)的情況
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);
}
}
//動(dòng)態(tài)sql時(shí)的判斷條件不會(huì)出現(xiàn)在ParameterMapping中,但是必須有,所以這里需要收集所有的getter屬性
//TypeHandlerRegistry可以直接處理的會(huì)作為一個(gè)直接使用的對(duì)象進(jìn)行處理
boolean hasTypeHandler = ms.getConfiguration().getTypeHandlerRegistry().hasTypeHandler(parameterObject.getClass());
MetaObject metaObject = MetaObjectUtil.forObject(parameterObject);
//需要針對(duì)注解形式的MyProviderSqlSource保存原值
if (!hasTypeHandler) {
for (String name : metaObject.getGetterNames()) {
paramMap.put(name, metaObject.getValue(name));
}
}
//下面這段方法,主要解決一個(gè)常見類型的參數(shù)時(shí)的問(wèn)題
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());
//處理參數(shù)配置
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中獲取的參數(shù),此處不再描述
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代碼實(shí)現(xiàn)
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處理查詢參數(shù)及查詢結(jié)果
攔截器:攔截update,query方法
處理查詢參數(shù)及返回結(jié)果。
/**
* 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;
}
//查詢參數(shù)加密處理
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]);
}
//查詢結(jié)果解密處理
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"/>
<!-- 自動(dòng)掃描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>
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java使用 try-with-resources 實(shí)現(xiàn)自動(dòng)關(guān)閉資源的方法
這篇文章主要介紹了Java使用 try-with-resources 實(shí)現(xiàn)自動(dòng)關(guān)閉資源的方法,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
深入分析@Resource和@Autowired注解區(qū)別
這篇文章主要為大家介紹了深入分析@Resource和@Autowired注解區(qū)別,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
intelliJ IDEA 多行選中相同內(nèi)容的快捷鍵分享
這篇文章主要介紹了intelliJ IDEA 多行選中相同內(nèi)容的快捷鍵分享,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02
詳解在springmvc中解決FastJson循環(huán)引用的問(wèn)題
本篇文章主要介紹了在springmvc中解決FastJson循環(huán)引用的問(wèn)題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01

