Springboot的Mybatis拦截器实现[通俗易懂]

Springboot的Mybatis拦截器实现[通俗易懂]MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,其实就是拦截器功能MyBatis允许拦截的接口MyBatis允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis允许使用插件来拦截的方法调用包括:Executor(update,query,fl…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,其实就是拦截器功能

MyBatis 允许拦截的接口

MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:

  1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  2. ParameterHandler (getParameterObject, setParameters)
  3. ResultSetHandler (handleResultSets, handleOutputParameters)
  4. StatementHandler (prepare, parameterize, batch, update, query)

Executor接口的部分方法,比如update,query,commit,rollback等方法,还有其他接口的一些方法等。

总体概括为:

  1. 拦截执行器的方法
  2. 拦截参数的处理
  3. 拦截结果集的处理,为sql执行之后的结果拦截过滤
  4. 拦截Sql语法构建的处理,为sql执行之前的拦截进行sql封装

MyBatis拦截器的接口定义

一共有三个方法interceptpluginsetProperties

setProperties()

方法主要是用来从配置中获取属性。

如果是使用xml式配置拦截器,可在Mybatis配置文件中添加如下节点,属性可以以如下方式传递

<plugins>
	<plugin interceptor="tk.mybatis.simple.plugin.XXXInterceptor">
		<property name="propl" value="valuel" />
		<property name="prop2" value="value2" />
	</plugin>
</plugins>

如果在Spring boot中使用,则需要单独写一个配置类,如下:

@Configuration
public class MybatisInterceptorConfig { 
   
    @Bean
    public String myInterceptor(SqlSessionFactory sqlSessionFactory) { 
   
        ExecutorInterceptor executorInterceptor = new ExecutorInterceptor();
        Properties properties = new Properties();
        properties.setProperty("prop1","value1");
        executorInterceptor.setProperties(properties);
        return "interceptor";
    }
}

如果说不需要配置属性,则在spring boot中,不需要去编写配置类,只需要像我一样在拦截器上加个@Component即可。

plugin()

方法用于指定哪些方法可以被此拦截器拦截。

intercept()

方法是用来对拦截的sql进行具体的操作。

注解实现

MyBatis拦截器用到了两个注解:@Intercepts@Signature

@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}),
        }
)

type的值与类名相同,method方法名相同,为了避免方法重载,args中指定了各个参数的类型和个数,可通过invocation.getArgs()获取参数数组。

Executor 拦截器实现

@Intercepts({ 
   
        @Signature(
        type= Executor.class,
        method = "query",
        args = { 
   MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
        )
})
@Slf4j
@Component
public class ExecutorInterceptor implements Interceptor { 
   
    @Override
    public Object intercept(Invocation invocation) throws Throwable { 
   
        String sql = ExecutorPluginUtils.getSqlByInvocation(invocation);
        //可以对sql重写
        log.error("拦截器ExecutorInterceptor:"+sql);
        //sql = "SELECT id from BUS_RECEIVER where id = ? ";
        ExecutorPluginUtils.resetSql2Invocation( invocation,  sql);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) { 
   
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) { 
   

    }


}

ParameterHandler 拦截器实现

/** * @Author: ynz * @Date: 2018/12/23/023 12:07 */
@Intercepts({ 
   
        @Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
})
@Component
@Slf4j
public class ParamInterceptor  implements Interceptor { 
   

    @Override
    public Object intercept(Invocation invocation) throws Throwable { 
   

        log.error("拦截器ParamInterceptor");
        //拦截 ParameterHandler 的 setParameters 方法 动态设置参数
        if (invocation.getTarget() instanceof ParameterHandler) { 
   
            ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();
            PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];

            // 反射获取 BoundSql 对象,此对象包含生成的sql和sql的参数map映射
            Field boundSqlField = parameterHandler.getClass().getDeclaredField("boundSql");
            boundSqlField.setAccessible(true);
            BoundSql boundSql = (BoundSql) boundSqlField.get(parameterHandler);
            // 反射获取 参数对像
            Field parameterField = 
                    parameterHandler.getClass().getDeclaredField("parameterObject");
            parameterField.setAccessible(true);
            Object parameterObject = parameterField.get(parameterHandler);

            if (parameterObject instanceof Map) { 
   
                //将参数中的name值改为2
                ((Map) parameterObject).put("name","2");
            }

            // 改写的参数设置到原parameterHandler对象
            parameterField.set(parameterHandler, parameterObject);
            parameterHandler.setParameters(ps);


            log.error(JSON.toJSONString(boundSql.getParameterMappings()));
            log.error(JSON.toJSONString(parameterObject));
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) { 
   
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) { 
   

    }
}

ResultSetHandler 拦截器实现

@Intercepts({ 
   
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args={ 
   Statement.class})
})
@Component
@Slf4j
public class ResultInterceptor implements Interceptor { 
   

    @Override
    public Object intercept(Invocation invocation) throws Throwable { 
   
        log.error("拦截器ResultInterceptor");
       // ResultSetHandler resultSetHandler1 = (ResultSetHandler) invocation.getTarget();
        //通过java反射获得mappedStatement属性值
        //可以获得mybatis里的resultype
        Object result = invocation.proceed();
        if (result instanceof ArrayList) { 
   
            ArrayList resultList = (ArrayList) result;
            for (int i = 0; i < resultList.size(); i++) { 
   
                Object oi = resultList.get(i);
                Class c = oi.getClass();
                Class[] types = { 
   String.class};
                Method method = c.getMethod("setAddress", types);
                // 调用obj对象的 method 方法
                method.invoke(oi, "china");
            }
        }
        return result;
    }

    @Override
    public Object plugin(Object target) { 
   
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) { 
   

    }
}

StatementHandler 拦截器实现

/** * @Author: ynz * @Date: 2018/12/23/023 14:22 */
@Intercepts(
        { 
   @Signature(
                type = StatementHandler.class,
                method = "prepare",
                args = { 
   Connection.class, Integer.class}
                )
        })
@Component
@Slf4j
public class StatementInterceptor implements Interceptor { 
   

    @Override
    public Object intercept(Invocation invocation) throws Throwable { 
   
        StatementHandler statementHandler = 
                (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
        MappedStatement mappedStatement = 
                (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
        //只拦截select方法
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) { 
   
            return invocation.proceed();
        }
        BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
        //获取到sql
        String originalSql = boundSql.getSql();
        //可以对originalSql进行改写
        log.error("拦截器StatementInterceptor:"+originalSql);
        metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
        Object parameterObject = boundSql.getParameterObject();
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) { 
   
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) { 
   

    }
}

Spring Boot整合

方法1:手写一个配置类

@Configuration
public class MybatisInterceptorConfig { 
   
    @Bean
    public String myInterceptor(SqlSessionFactory sqlSessionFactory) { 
   
        ExecutorInterceptor executorInterceptor = new ExecutorInterceptor();
        Properties properties = new Properties();
        properties.setProperty("prop1","value1");
        executorInterceptor.setProperties(properties);
        sqlSessionFactory.getConfiguration().addInterceptor(executorInterceptor);
        sqlSessionFactory.getConfiguration().addInterceptor(new ParamInterceptor());
        sqlSessionFactory.getConfiguration().addInterceptor(new ResultInterceptor());
        return "interceptor";
    }
}

方法2:在拦截器上加@Component注解

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/195748.html原文链接:https://javaforall.net

(0)
上一篇 2025年10月11日 上午9:43
下一篇 2025年10月11日 上午10:15


相关推荐

  • 因果图和判定表_因果判定法

    因果图和判定表_因果判定法 上一篇文章中介绍了等价类和边界值,接下来我们就来学习一下因果图和判定表,这两种方法在软件测试中是非常重要的工具,这两个东西理论也是很绕口,特别是因果图,砖家给的方法我看起来也很困,所以我们就不要按照砖家的思路来。定义因果图法是一种利用图解法分析输入的各种组合情况,从而设计测试用例的方法,它适合于检查程序输入条件的各种组合情况。 特点:a考虑输入条件的相互制约及组合关系b考虑输出条件对输…

    2022年8月14日
    9
  • kill命令详解_linux杀死进程kill

    kill命令详解_linux杀死进程kill大多数人对kill命令的理解就是杀死一个进程,而这仅仅是kill的一个功能。Kill的zhenshkill用途是向一个进程发送信号,而杀死一个进程仅仅是其中的一个功能。

    2025年7月28日
    4
  • 怎么判断Long类型为空_java将list转为string

    怎么判断Long类型为空_java将list转为stringList<String>和List<Long>类型相互转化 jdk 8.0 新特性

    2022年4月20日
    629
  • 编写自己的who命令

    编写自己的who命令
    今天自己照着书一步步敲了who命令的实现。老外写的有些书就是不错,一步步启发你告诉你怎么思考,怎么根据已有的线索查询联机帮助,怎么一步步最终解决问题。真不错。
    下面我就根据书上的思想,来回顾一下这将近2个小时的工作。

    1.who命令能

    2022年6月11日
    33
  • zipfile模块使用「建议收藏」

    zipfile模块使用「建议收藏」zipfile模块zipfile说明zipfile的常用方法:is_zipfile():ZipFile类的常用方法:ZipFile():ZipFile.close():ZipFile.getinfo(),ZipFile.infolist()和ZipFile.namelist()ZipFile.extract()和ZipFile.extractall()ZipFile.printdir()和ZipFile.read()ZipFile.write()和ZipFile.writestr():ZipInfo类的常用

    2025年12月13日
    3
  • Java知识体系最强总结(2021版)[通俗易懂]

    更新于2019-12-1510:38:00本人从事Java开发已多年,平时有记录问题解决方案和总结知识点的习惯,整理了一些有关Java的知识体系,这不是最终版,会不定期的更新。也算是记录自己在从事编程工作的成长足迹,通过博客可以促进博主与阅读者的共同进步,结交更多志同道合的朋友。特此分享给大家,本人见识有限,写的博客难免有错误或者疏忽的地方,还望各位大佬指点,在此表示感激不尽。文章目录…

    2022年4月6日
    52

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号