您好,登錄后才能下訂單哦!
本篇內容主要講解“MyBatis攔截器怎么動態替換表名”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“MyBatis攔截器怎么動態替換表名”吧!
簡單的說就是mybatis在執行sql的時候,攔截目標方法并且在前后加上我們的業務邏輯。實際上就是加@Intercepts注解和實現org.apache.ibatis.plugin.Interceptor
接口
@Intercepts( @Signature(method = "query", type = Executor.class, args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class} ) )
public interface Interceptor { //主要重寫這個方法、實現我們的業務邏輯 Object intercept(Invocation invocation) throws Throwable; //生成代理對象,可以在這里判斷是否生成代理對象 Object plugin(Object target); //如果我們攔截器需要用到一些變量參數,可以在這里讀取 void setProperties(Properties properties); }
在intercept方法中有參數Invocation對象,里面有3個成員變量和@Signature對應
成員變量 | 變量類型 | 說明 |
---|---|---|
target | Object | 代理對象 |
method | Method | 被攔截方法 |
args | Object[] | 被攔截方法執行所需的參數 |
通過Invocation中的args變量。我們能拿到MappedStatement這個對象(args[0]),傳入sql語句的參數Object(args[1])。而MappedStatement是一個記錄了sql語句(sqlSource對象)、參數值結構、返回值結構、mapper配置等的一個對象。
sqlSource對象和傳入sql語句的參數對象Object就能獲得BoundSql。BoundSql的toString方法就能獲取到有占位符的sql語句了,我們的業務邏輯就能在這里介入。
獲取到sql語句,根據規則替換表名,塞回BoundSql對象中、再把BoundSql對象塞回MappedStatement對象中。最后再賦值給args[0](實際被攔截方法所需的參數)就搞定了
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: 動態替換表名攔截器 * @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語句的參數對象 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)); //賦回給實際執行方法所需的參數中 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; } /*** * 復制一個新的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構造器接受的是SqlSource * 實現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; } } }
到此,相信大家對“MyBatis攔截器怎么動態替換表名”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。