欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-30 10:17:04
目录前言定义是否开启注解注册sql 拦截器处理逻辑如何使用总结前言本文主要是讲通过 mybaits 的 interceptor 的拓展点进行对 mybatis 执行 sql 之前做一个逻辑拦截实现自定...

前言

本文主要是讲通过 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拦截器内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

上一篇:

下一篇: