欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MyBatis攔截器動態(tài)替換表名的方法詳解

 更新時間:2022年04月24日 11:55:28   作者:hinotoyk  
因為我們持久層框架更多地使用MyBatis,那我們就借助于MyBatis的攔截器來完成我們的功能,這篇文章主要給大家介紹了關于MyBatis攔截器動態(tài)替換表名的相關資料,需要的朋友可以參考下

寫在前面

今天收到一個需求,根據請求方的不同,動態(tài)的切換表名(涵蓋SELECT,INSERT,UPDATE操作)。幾張新表和舊表的結構完全一致,但是分開維護??吹叫枨蟮谝环磻菍⒈砻岢鰜懋?{tableName}參數(shù),然后AOP攔截判斷再替換表名。但是后面看了一下這幾張表在很多mapper接口都有使用,其中還有一些復雜的連接查詢,提取tableName當參數(shù)肯定是不現(xiàn)實的了。后面和組內大佬討論之后,發(fā)現(xiàn)可以使用MyBatis提供的攔截器,判斷并且動態(tài)的替換表名。

一、Mybatis Interceptor 攔截器接口和注解

簡單的說就是mybatis在執(zhí)行sql的時候,攔截目標方法并且在前后加上我們的業(yè)務邏輯。實際上就是加@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è)務邏輯
  Object intercept(Invocation invocation) throws Throwable;
  
  //生成代理對象,可以在這里判斷是否生成代理對象
  Object plugin(Object target);
  
  //如果我們攔截器需要用到一些變量參數(shù),可以在這里讀取
  void setProperties(Properties properties);
}

二、實現(xiàn)思路

  • 在intercept方法中有參數(shù)Invocation對象,里面有3個成員變量和@Signature對應
成員變量變量類型說明
targetObject代理對象
methodMethod被攔截方法
argsObject[]被攔截方法執(zhí)行所需的參數(shù)
  • 通過Invocation中的args變量。我們能拿到MappedStatement這個對象(args[0]),傳入sql語句的參數(shù)Object(args[1])。而MappedStatement是一個記錄了sql語句(sqlSource對象)、參數(shù)值結構、返回值結構、mapper配置等的一個對象。
  • sqlSource對象和傳入sql語句的參數(shù)對象Object就能獲得BoundSql。BoundSql的toString方法就能獲取到有占位符的sql語句了,我們的業(yè)務邏輯就能在這里介入。
  • 獲取到sql語句,根據規(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;
    }

    /***
     * 復制一個新的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
     * 實現(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;
        }
    }
}

四、運行結果

寫在最后

一開始接到這個需求的時候,會習慣性的從熟悉常用的技術入手。如果涉及的表引用沒這么多,是不是就會直接用AOP攔截判斷替換了呢,我大概率是會的??赡芫筒粫氲缴厦娴臄r截器動態(tài)替換的方法(相當于失去一次學習的機會),還是要跳出慣性多思考還有沒有更合適的做法,把每次需求都當成一次學習的機會,舒適圈都能變開闊很多,共勉。

參考資料

MyBatis官網

mybatis插件實現(xiàn)自定義改寫表名

到此這篇關于MyBatis攔截器動態(tài)替換表名的文章就介紹到這了,更多相關MyBatis動態(tài)替換表名內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論