MyBatis攔截器動態(tài)替換表名的方法詳解
寫在前面
今天收到一個需求,根據(jù)請求方的不同,動態(tài)的切換表名(涵蓋SELECT,INSERT,UPDATE操作)。幾張新表和舊表的結(jié)構(gòu)完全一致,但是分開維護。看到需求第一反應(yīng)是將表名提出來當(dāng)${tableName}參數(shù),然后AOP攔截判斷再替換表名。但是后面看了一下這幾張表在很多mapper接口都有使用,其中還有一些復(fù)雜的連接查詢,提取tableName當(dāng)參數(shù)肯定是不現(xiàn)實的了。后面和組內(nèi)大佬討論之后,發(fā)現(xiàn)可以使用MyBatis提供的攔截器,判斷并且動態(tài)的替換表名。
一、Mybatis Interceptor 攔截器接口和注解
簡單的說就是mybatis在執(zhí)行sql的時候,攔截目標(biāo)方法并且在前后加上我們的業(yè)務(wù)邏輯。實際上就是加@Intercepts注解和實現(xiàn)org.apache.ibatis.plugin.Interceptor
接口
@Intercepts( @Signature(method = "query", type = Executor.class, args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class} ) )
public interface Interceptor { //主要重寫這個方法、實現(xiàn)我們的業(yè)務(wù)邏輯 Object intercept(Invocation invocation) throws Throwable; //生成代理對象,可以在這里判斷是否生成代理對象 Object plugin(Object target); //如果我們攔截器需要用到一些變量參數(shù),可以在這里讀取 void setProperties(Properties properties); }
二、實現(xiàn)思路
- 在intercept方法中有參數(shù)Invocation對象,里面有3個成員變量和@Signature對應(yīng)
成員變量 | 變量類型 | 說明 |
---|---|---|
target | Object | 代理對象 |
method | Method | 被攔截方法 |
args | Object[] | 被攔截方法執(zhí)行所需的參數(shù) |
- 通過Invocation中的args變量。我們能拿到MappedStatement這個對象(args[0]),傳入sql語句的參數(shù)Object(args[1])。而MappedStatement是一個記錄了sql語句(sqlSource對象)、參數(shù)值結(jié)構(gòu)、返回值結(jié)構(gòu)、mapper配置等的一個對象。
- sqlSource對象和傳入sql語句的參數(shù)對象Object就能獲得BoundSql。BoundSql的toString方法就能獲取到有占位符的sql語句了,我們的業(yè)務(wù)邏輯就能在這里介入。
- 獲取到sql語句,根據(jù)規(guī)則替換表名,塞回BoundSql對象中、再把BoundSql對象塞回MappedStatement對象中。最后再賦值給args[0](實際被攔截方法所需的參數(shù))就搞定了
三、代碼實現(xiàn)
import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.plugin.*; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.*; /** * @description: 動態(tài)替換表名攔截器 * @author: hinotoyk * @created: 2022/04/19 */ //method = "query"攔截select方法、而method = "update"則能攔截insert、update、delete的方法 @Intercepts({ @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) }) public class ReplaceTableInterceptor implements Interceptor { private final static Map<String,String> TABLE_MAP = new LinkedHashMap<>(); static { //表名長的放前面,避免字符串匹配的時候先匹配替換子集 TABLE_MAP.put("t_game_partners","t_game_partners_test");//測試 TABLE_MAP.put("t_file_recycle","t_file_recycle_other"); TABLE_MAP.put("t_folder","t_folder_other"); TABLE_MAP.put("t_file","t_file_other"); } @Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); //獲取MappedStatement對象 MappedStatement ms = (MappedStatement) args[0]; //獲取傳入sql語句的參數(shù)對象 Object parameterObject = args[1]; BoundSql boundSql = ms.getBoundSql(parameterObject); //獲取到擁有占位符的sql語句 String sql = boundSql.getSql(); System.out.println("攔截前sql :" + sql); //判斷是否需要替換表名 if(isReplaceTableName(sql)){ for(Map.Entry<String, String> entry : TABLE_MAP.entrySet()){ sql = sql.replace(entry.getKey(),entry.getValue()); } System.out.println("攔截后sql :" + sql); //重新生成一個BoundSql對象 BoundSql bs = new BoundSql(ms.getConfiguration(),sql,boundSql.getParameterMappings(),parameterObject); //重新生成一個MappedStatement對象 MappedStatement newMs = copyMappedStatement(ms, new BoundSqlSqlSource(bs)); //賦回給實際執(zhí)行方法所需的參數(shù)中 args[0] = newMs; } return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } /*** * 判斷是否需要替換表名 * @param sql * @return */ private boolean isReplaceTableName(String sql){ for(String tableName : TABLE_MAP.keySet()){ if(sql.contains(tableName)){ return true; } } return false; } /*** * 復(fù)制一個新的MappedStatement * @param ms * @param newSqlSource * @return */ private MappedStatement copyMappedStatement (MappedStatement ms, SqlSource newSqlSource) { MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType()); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) { builder.keyProperty(String.join(",",ms.getKeyProperties())); } builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); builder.resultMaps(ms.getResultMaps()); builder.resultSetType(ms.getResultSetType()); builder.cache(ms.getCache()); builder.flushCacheRequired(ms.isFlushCacheRequired()); builder.useCache(ms.isUseCache()); return builder.build(); } /*** * MappedStatement構(gòu)造器接受的是SqlSource * 實現(xiàn)SqlSource接口,將BoundSql封裝進去 */ public static class BoundSqlSqlSource implements SqlSource { private BoundSql boundSql; public BoundSqlSqlSource(BoundSql boundSql) { this.boundSql = boundSql; } @Override public BoundSql getBoundSql(Object parameterObject) { return boundSql; } } }
四、運行結(jié)果
寫在最后
一開始接到這個需求的時候,會習(xí)慣性的從熟悉常用的技術(shù)入手。如果涉及的表引用沒這么多,是不是就會直接用AOP攔截判斷替換了呢,我大概率是會的??赡芫筒粫氲缴厦娴臄r截器動態(tài)替換的方法(相當(dāng)于失去一次學(xué)習(xí)的機會),還是要跳出慣性多思考還有沒有更合適的做法,把每次需求都當(dāng)成一次學(xué)習(xí)的機會,舒適圈都能變開闊很多,共勉。
參考資料
到此這篇關(guān)于MyBatis攔截器動態(tài)替換表名的文章就介紹到這了,更多相關(guān)MyBatis動態(tài)替換表名內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?Boot讀取配置文件內(nèi)容的3種方式(@Value、Environment和@ConfigurationP
工作中經(jīng)常會有一些參數(shù)需要配置,同時在代碼里面需要用到,所有就需要配置類讀取,然后在使用的時候注入該類進行獲取相關(guān)參數(shù),下面這篇文章主要給大家介紹了關(guān)于Spring?Boot讀取配置文件內(nèi)容的3種方式,需要的朋友可以參考下2023-01-01springboot使用小工具之Lombok、devtools、Spring Initailizr詳解
這篇文章主要介紹了springboot使用小工具之Lombok、devtools、Spring Initailizr詳解,Lombok可以代替手寫get、set、構(gòu)造方法等,需要idea裝插件lombok,本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10SpringBoot項目調(diào)優(yōu)及垃圾回收器的比較詳解
這篇文章主要介紹了SpringBoot項目調(diào)優(yōu)及垃圾回收器的比較詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04基于JAVA中Jersey處理Http協(xié)議中的Multipart的詳解
之前在基于C#開發(fā)彩信用最原始的StringBuilder拼接字符串方式處理過Multipart?,F(xiàn)在在做一個項目的時候,由于之前的技術(shù)路線都是使用Jersey處理Http這塊,為了保持技術(shù)路線一致,研究了一下如何使用Jersey處理Http協(xié)議中的Multipart2013-05-05詳解Java如何在CompletableFuture中實現(xiàn)日志記錄
這篇文章主要為大家詳細(xì)介紹了一種slf4j自帶的MDC類,來記錄完整的請求日志,和在CompletableFuture異步線程中如何保留鏈路id,需要的可以參考一下2023-04-04Java Arrays.sort和Collections.sort排序?qū)崿F(xiàn)原理解析
這篇文章主要介紹了Java Arrays.sort和Collections.sort排序?qū)崿F(xiàn)原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02使用@TableField(updateStrategy=FieldStrategy.IGNORED)遇到的坑記錄
這篇文章主要介紹了使用@TableField(updateStrategy=FieldStrategy.IGNORED)遇到的坑及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11