MyBatis自定义SQL拦截器示例详解


Posted in Java/Android onOctober 24, 2021

前言

本文主要是讲通过 MyBaits 的 Interceptor 的拓展点进行对 MyBatis 执行 SQL 之前做一个逻辑拦截实现自定义逻辑的插入执行。

适合场景:1. 比如限制数据库查询最大访问条数;2. 限制登录用户只能访问当前机构数据。

定义是否开启注解

定义是否开启注解, 主要做的一件事情就是是否添加 SQL 拦截器。

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

}

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

}

注册SQL 拦截器

注册一个 SQL 拦截器,会对符合条件的 SQL 查询操作进行拦截。

public class MyBatisSqlInterceptorConfiguration implements ApplicationContextAware {

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

处理逻辑

在处理逻辑中,我主要是做一个简单的 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;
        //由于逻辑关系,只会进入一次
        if (args.length == 4) {
            //4 个参数时
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        } else {
            //6 个参数时
            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一个查询语句对象
            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);
    }

    /**
     * 定义一个内部辅助类,作用是包装 SQL
     */
    class BoundSqlSource implements SqlSource {
        private BoundSql boundSql;

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

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

    }

}

如何使用

我们在 XXXMapper 中对应的数据操作方法只要加入 @DataScope 注解即可。

@Mapper
public interface OrderMapper {

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

}

参考资料

mybatis.org/mybatis-3/z

总结

到此这篇关于MyBatis自定义SQL拦截器的文章就介绍到这了,更多相关MyBatis自定义SQL拦截器内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Java/Android 相关文章推荐
JVM入门之类加载与字节码技术(类加载与类的加载器)
Jun 15 Java/Android
SpringAop日志找不到方法的处理
Jun 21 Java/Android
java基础——多线程
Jul 03 Java/Android
详细了解MVC+proxy
Jul 09 Java/Android
详解Java七大阻塞队列之SynchronousQueue
Sep 04 Java/Android
Spring Security中用JWT退出登录时遇到的坑
Oct 16 Java/Android
SpringBoot2零基础到精通之数据与页面响应
Mar 22 Java/Android
Dubbo+zookeeper搭配分布式服务的过程详解
Apr 03 Java/Android
Java版 简易五子棋小游戏
May 04 Java/Android
openGauss数据库JDBC环境连接配置的详细过程(Eclipse)
Jun 01 Java/Android
Java实现带图形界面的聊天程序
Jun 10 Java/Android
Spring JPA 增加字段执行异常问题及解决
Jun 10 Java/Android
java多态注意项小结
Spring Security中用JWT退出登录时遇到的坑
Java实现房屋出租系统详解
Oct 05 #Java/Android
Java Spring 控制反转(IOC)容器详解
Java spring定时任务详解
JAVA API 实用类 String详解
Oct 05 #Java/Android
SpringCloud之@FeignClient()注解的使用方式
Sep 25 #Java/Android
You might like
QQ登录 PHP OAuth示例代码
2011/07/20 PHP
PHP中file_exists()判断中文文件名无效的解决方法
2014/11/12 PHP
PHP结合Jquery和ajax实现瀑布流特效
2016/01/07 PHP
PHP查询大量数据内存耗尽问题的解决方法
2016/10/28 PHP
javascript截取字符串(通过substring实现并支持中英文混合)
2013/06/24 Javascript
浅析js封装和作用域
2013/07/09 Javascript
Nodejs学习笔记之测试驱动
2015/04/16 NodeJs
jQuery实现移动端滑块拖动选择数字效果
2015/12/24 Javascript
Bootstrap安装环境配置教程分享
2016/05/27 Javascript
深入分析node.js的异步API和其局限性
2016/09/05 Javascript
JavaScript实现左右下拉框动态增删示例
2017/03/09 Javascript
js操作二进制数据方法
2018/03/03 Javascript
如何基于vue-cli3.0构建功能完善的移动端架子
2019/04/24 Javascript
多个vue子路由文件自动化合并的方法
2019/09/03 Javascript
layui table数据修改的回显方法
2019/09/04 Javascript
微信小程序修改checkbox的样式代码实例
2020/01/21 Javascript
ant-design-vue中tree增删改的操作方法
2020/11/03 Javascript
Python实现快速多线程ping的方法
2015/07/15 Python
python中如何使用分步式进程计算详解
2019/03/22 Python
python制作图片缩略图
2019/04/30 Python
浅谈python 中类属性共享的问题
2019/07/02 Python
Python使用pycharm导入pymysql教程
2020/09/16 Python
python 实现控制鼠标键盘
2020/11/27 Python
亚洲最大的眼镜批发商和零售商之一:Glasseslit
2018/10/08 全球购物
Rowdy Gentleman服装和配饰:美好时光
2019/09/24 全球购物
横幅标语大全
2014/06/17 职场文书
学习普通话的体会
2014/11/07 职场文书
民政局标准版离婚协议书
2014/12/01 职场文书
2015年学习部工作总结范文
2015/03/31 职场文书
婚宴祝酒词大全
2015/08/10 职场文书
社区服务活动感想
2015/08/11 职场文书
django上传文件的三种方式
2021/04/29 Python
Python采集股票数据并制作可视化柱状图
2022/04/04 Python
Flutter集成高德地图并添加自定义Maker的实践
2022/04/07 Java/Android
Golang map映射的用法
2022/04/22 Golang
MYSQL事务的隔离级别与MVCC
2022/05/25 MySQL