Mybatis框架中Interceptor接口的使用說明
Mybatis Interceptor接口的使用
關(guān)于Mybatis中插件的聲明需要在configuration的配置文件中進(jìn)行配置,配置文件的位置使用configLocation屬性指定。
測試中使用的config文件內(nèi)容如下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--plugins插件之 分頁攔截器 --> <plugins> <plugin interceptor="com.interceptors.LogInterceptor" ></plugin> </plugins> </configuration>
在配置文件中配置了一個Interceptor的實現(xiàn)類
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; //打印出當(dāng)前執(zhí)行的sql語句 System.out.println(handler.getBoundSql().getSql()); } return target; } @Override public void setProperties(Properties properties) { System.out.println("LogInterceptor : setProperties"); } }
在工程的配置文件中,在配置SqlSessionFactoryBean時需要指明config配置文件的位置,配置文件如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="user1" class="com.beans.User"> <property name="userName" value="zhuyuqiang"/> </bean> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="name" value="mysql"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/world"/> <property name="username" value="root"/> <property name="password" value="zh4y4q5ang"/> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath:mybatis/*.xml"/> <property name="typeAliasesPackage" value="com.entities"/> <property name="configLocation" value="classpath:config/configuration.xml"/> </bean> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.interfaces"/> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <context:component-scan base-package="com"/> </beans>
基本上這樣配置以后,在工程中聲明的plugin就已經(jīng)生效了,實際中打印出來的log如下:
SELECT * FROM city WHERE ID=?
執(zhí)行的CityMapper如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.interfaces.CityMapper"> <resultMap id="BaseResultMap" type="com.entities.City"> <id column="ID" jdbcType="INTEGER" property="id"/> <result column="Name" jdbcType="CHAR" property="name"/> <result column="CountryCode" jdbcType="CHAR" property="countrycode"/> <result column="District" jdbcType="CHAR" property="district"/> <result column="Population" jdbcType="INTEGER" property="population"/> </resultMap> <select id="selectCityById" parameterType="int" resultType="com.entities.City"> SELECT * FROM city WHERE ID=#{id,jdbcType=INTEGER} </select> </mapper>
簡單的測試了一下,可以打印出sql語句。在使用mybatis提供的plugin接口時需要注意,在構(gòu)建ParameterHandler 、ResultSetHandler 、StatementHandler 和Executor 的時候都會調(diào)用在項目中實現(xiàn)的插件接口,一般情況下,如果只是為了打印顯示當(dāng)前執(zhí)行的sql語句,可以只在當(dāng)target為StatementHandler類型的時候再進(jìn)行處理即可。
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; }
在實際測操作中,在項目中定義實現(xiàn)的plugin都會被添加保存到interceptorChain對象的一個集合中,在內(nèi)部會對集合里的對象進(jìn)行遍歷,分別調(diào)用每個插件的plugin方法。
其中target就是在調(diào)用pluginAll傳入的具體對象。。。
Interceptor修改執(zhí)行sql及傳入?yún)?shù)
項目中途遇到業(yè)務(wù)需求更改,在查詢某張表時需要增加條件,由于涉及的sql語句多而且依賴其他服務(wù)的jar,逐個修改sql語句和接口太繁雜。項目使用mybatis框架,因此借鑒PageHelper插件嘗試使用mybatis的Interceptor來實現(xiàn)改需求。
總體思路
- 從BoundSql中獲取sql,通過正則匹配替換表名為子查詢REPLACE_TXT
- 添加子查詢REPLACE_TXT 中需要用到的參數(shù)到mybatis參數(shù)列表中
- 添加參數(shù)與占位符映射,即添加ParameterMapping對象到ParameterMappings中,由于statement在執(zhí)行時是按照ParameterMappings的元素索引定位占位符封裝參數(shù)(即ParameterMappings中的第一個參數(shù)會封裝到第一個占位符上),因此ParameterMappings中的參數(shù)順序需要和占位符保持一致。其次ParameterMappings的元素個數(shù)需要和占位符個數(shù)保持一致。
- 為了保證該intercept在最后執(zhí)行,使用AutoConfiguration將intercept添加到SqlSessionFactory的Configuration中,并在spring.factories文件中添加AutoConfiguration
- 未測試性能以及是否存在未知缺陷
1、Interceptor 代碼實現(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攔截器對查詢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語句,使用正則忽略大小寫匹配 String sql = boundSql.getSql(); Matcher matcher = DW_DIMCOMPANY.matcher(sql); //沒有需要替換的表名則放行 if(!matcher.find()){ return invocation.proceed(); } //收集占位符個數(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è)置動態(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時,處理只有1個參數(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); } } //動態(tài)sql時的判斷條件不會出現(xiàn)在ParameterMapping中,但是必須有,所以這里需要收集所有的getter屬性 //TypeHandlerRegistry可以直接處理的會作為一個直接使用的對象進(jìn)行處理 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)); } } //下面這段方法,主要解決一個常見類型的參數(shù)時的問題 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代碼實現(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); } } }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot結(jié)合Redis實現(xiàn)緩存
本文主要介紹了SpringBoot結(jié)合Redis實現(xiàn)緩存,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06SpringBoot結(jié)合ProGuard實現(xiàn)代碼混淆(最新版)
這篇文章主要介紹了SpringBoot結(jié)合ProGuard實現(xiàn)代碼混淆(最新版),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10java中用float時,數(shù)字后面加f,這樣是為什么你知道嗎
這篇文章主要介紹了java用float時,數(shù)字后面加f,這樣是為什么你知道嗎?具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09Spring?boot?security權(quán)限管理集成cas單點登錄功能的實現(xiàn)
這篇文章主要介紹了Spring?boot?security權(quán)限管理集成cas單點登錄,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03Mybatis中傳遞多個參數(shù)的4種方法總結(jié)
這篇文章主要給大家介紹了關(guān)于Mybatis中傳遞多個參數(shù)的4種方法,并且介紹了關(guān)于使用Mapper接口時參數(shù)傳遞方式,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-04-04