最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

MyBatis自定義SQL攔截器示例詳解

 更新時(shí)間:2021年10月24日 12:01:16   作者:老鄭_  
Mybatis支持對Executor、StatementHandler、PameterHandler和ResultSetHandler 接口進(jìn)行攔截,也就是說會(huì)對這4種對象進(jìn)行代理,下面這篇文章主要給大家介紹了關(guān)于MyBatis自定義SQL攔截器的相關(guān)資料,需要的朋友可以參考下

前言

本文主要是講通過 MyBaits 的 Interceptor 的拓展點(diǎn)進(jìn)行對 MyBatis 執(zhí)行 SQL 之前做一個(gè)邏輯攔截實(shí)現(xiàn)自定義邏輯的插入執(zhí)行。

適合場景:1. 比如限制數(shù)據(jù)庫查詢最大訪問條數(shù);2. 限制登錄用戶只能訪問當(dāng)前機(jī)構(gòu)數(shù)據(jù)。

定義是否開啟注解

定義是否開啟注解, 主要做的一件事情就是是否添加 SQL 攔截器。

// 全局開啟
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MyBatisSqlInterceptorConfiguration.class)
public @interface EnableSqlInterceptor {

}

// 自定義注解
@Target({ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface DataScope {

}

注冊SQL 攔截器

注冊一個(gè) SQL 攔截器,會(huì)對符合條件的 SQL 查詢操作進(jìn)行攔截。

public class MyBatisSqlInterceptorConfiguration implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
        sqlSessionFactory.getConfiguration().addInterceptor(new MyBatisInterceptor());
    }
}


處理邏輯

在處理邏輯中,我主要是做一個(gè)簡單的 limit 1 案例,如果是自己需要做其他的邏輯需要修改

@Slf4j
@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 MyBatisInterceptor implements Interceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyBatisInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // TODO Auto-generated method stub
        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;
        //由于邏輯關(guān)系,只會(huì)進(jìn)入一次
        if (args.length == 4) {
            //4 個(gè)參數(shù)時(shí)
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        } else {
            //6 個(gè)參數(shù)時(shí)
            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }
        DataScope dataScope = getDataScope(ms);
        if (Objects.nonNull(dataScope)) {
            String origSql = boundSql.getSql();
            log.info("origSql : {}", origSql);
            // 組裝新的 sql
            // todo you weaving business
            String newSql = origSql + " limit 1";

            // 重新new一個(gè)查詢語句對象
            BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
                    boundSql.getParameterMappings(), boundSql.getParameterObject());

            // 把新的查詢放到statement里
            MappedStatement newMs = newMappedStatement(ms, new BoundSqlSource(newBoundSql));
            for (ParameterMapping mapping : boundSql.getParameterMappings()) {
                String prop = mapping.getProperty();
                if (boundSql.hasAdditionalParameter(prop)) {
                    newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
                }
            }

            args[0] = newMs;
            if (args.length == 6) {
                args[5] = newMs.getBoundSql(parameter);
            }
        }
        LOGGER.info("mybatis intercept sql:{},Mapper方法是:{}", boundSql.getSql(), ms.getId());


        return invocation.proceed();
    }

    private MappedStatement newMappedStatement(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(ms.getKeyProperties()[0]);
        }
        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();
    }


    private DataScope getDataScope(MappedStatement mappedStatement) {
        String id = mappedStatement.getId();
        // 獲取 Class Method
        String clazzName = id.substring(0, id.lastIndexOf('.'));
        String mapperMethod = id.substring(id.lastIndexOf('.') + 1);

        Class<?> clazz;
        try {
            clazz = Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            return null;
        }
        Method[] methods = clazz.getMethods();

        DataScope dataScope = null;
        for (Method method : methods) {
            if (method.getName().equals(mapperMethod)) {
                dataScope = method.getAnnotation(DataScope.class);
                break;
            }
        }
        return dataScope;
    }

    @Override
    public Object plugin(Object target) {
        // TODO Auto-generated method stub
        LOGGER.info("MysqlInterCeptor plugin>>>>>>>{}", target);
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
        String dialect = properties.getProperty("dialect");
        LOGGER.info("mybatis intercept dialect:>>>>>>>{}", dialect);
    }

    /**
     * 定義一個(gè)內(nèi)部輔助類,作用是包裝 SQL
     */
    class BoundSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }

    }

}

如何使用

我們在 XXXMapper 中對應(yīng)的數(shù)據(jù)操作方法只要加入 @DataScope 注解即可。

@Mapper
public interface OrderMapper {

   @Select("select 1 ")
   @DataScope
   Intger selectOne();

}

參考資料

mybatis.org/mybatis-3/z

總結(jié)

到此這篇關(guān)于MyBatis自定義SQL攔截器的文章就介紹到這了,更多相關(guān)MyBatis自定義SQL攔截器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • MyBatis里映射文件sql語句爆紅問題及解決方案

    MyBatis里映射文件sql語句爆紅問題及解決方案

    文章介紹了在MyBatis映射文件中SQL語句爆紅的問題及其解決方法,解決方法是在設(shè)置中將SQL的全局方言設(shè)為None,然后應(yīng)用并確認(rèn)設(shè)置即可
    2025-03-03
  • Java/Android引用類型及其使用全面分析

    Java/Android引用類型及其使用全面分析

    下面小編就為大家?guī)硪黄狫ava/Android引用類型及其使用全面分析。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-09-09
  • Java?Handler同步屏障淺析講解

    Java?Handler同步屏障淺析講解

    同步屏障機(jī)制是什么?Handler發(fā)送的消息分為普通消息、屏障消息、異步消息,一旦Looper在處理消息時(shí)遇到屏障消息,那么就不再處理普通的消息,而僅僅處理異步的消息。不再使用屏障后,需要撤銷屏障,不然就再也執(zhí)行不到普通消息了
    2022-08-08
  • SpringBoot 如何讀取classpath下的文件

    SpringBoot 如何讀取classpath下的文件

    這篇文章主要介紹了SpringBoot 讀取classpath下的文件方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Spring高級(jí)注解@PropertySource詳細(xì)解讀

    Spring高級(jí)注解@PropertySource詳細(xì)解讀

    這篇文章主要介紹了Spring高級(jí)注解@PropertySource詳細(xì)解讀,@PropertySource注解用于指定資源文件讀取的位置,它不僅能讀取properties文件,也能讀取xml文件,并且通過YAML解析器,配合自定義PropertySourceFactory實(shí)現(xiàn)解析yaml文件,需要的朋友可以參考下
    2023-11-11
  • Log4j_配置方法(全面講解)

    Log4j_配置方法(全面講解)

    下面小編就為大家?guī)硪黄狶og4j_配置方法(全面講解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-09-09
  • springBoot無法解析yml問題

    springBoot無法解析yml問題

    這篇文章主要介紹了springBoot無法解析yml問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • 深入了解Java核心類庫--String類

    深入了解Java核心類庫--String類

    這篇文章主要為大家詳細(xì)介紹了java String類定義與使用的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能給你帶來幫助
    2021-07-07
  • IDEA插件Statistic統(tǒng)計(jì)代碼快速分辨爛項(xiàng)目

    IDEA插件Statistic統(tǒng)計(jì)代碼快速分辨爛項(xiàng)目

    這篇文章主要為大家介紹了使用IDEA插件Statistic來統(tǒng)計(jì)項(xiàng)目代碼,幫助大家快速識(shí)別出爛項(xiàng)目,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2022-01-01
  • Springcloud Stream消息驅(qū)動(dòng)工具使用介紹

    Springcloud Stream消息驅(qū)動(dòng)工具使用介紹

    SpringCloud Stream由一個(gè)中間件中立的核組成,應(yīng)用通過SpringCloud Stream插入的input(相當(dāng)于消費(fèi)者consumer,它是從隊(duì)列中接收消息的)和output(相當(dāng)于生產(chǎn)者producer,它是發(fā)送消息到隊(duì)列中的)通道與外界交流
    2022-09-09

最新評論

长子县| 济阳县| 鹤岗市| 聊城市| 射阳县| 陆良县| 陆良县| 黎城县| 金溪县| 公主岭市| 万山特区| 含山县| 元谋县| 台江县| 凤庆县| 犍为县| 万源市| 德江县| 察雅县| 海阳市| 襄城县| 伊金霍洛旗| 伊宁县| 望谟县| 洪泽县| 大化| 南郑县| 洛南县| 乐平市| 磐石市| 永胜县| 通榆县| 民勤县| 漠河县| 余干县| 施秉县| 特克斯县| 六盘水市| 香港| 白城市| 广昌县|