概述
MyBatis允许在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis允许使用插件来拦截的方法调用包括:
·Executor(update,query,flushStatement,commit.rollback,getTransaction,close,isClosed)
·ParameterHandler(getParameterObject,setParameters)
·ResultSetHandler(handleResultSets,handleOutputParameters)
·StatementHandler(prepare,parameterize,batch,update,query)
这些类中方法的细节可以通过查看每个方法的签名来发现,或者直接查看MyBatis发行包中的源代码。
如果想做的不仅仅是监控方法的调用,那么最好相当了解要重写的方法的行为。
因为如果在试图修改或重写已有方法的行为的时候,很可能在破坏MyBatis的核心模块。
这些都是更低层的类和方法,所以使用插件的时候要特别当心。
通过MyBatis提供的强大机制,使用插件是非常简单的,只需要实现Interceptor接口,并指定想要拦截的方法签名即可。
// ExamplePlugin.java @Intercepts({@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})}) public class ExamplePlugin implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { return invocation.proceed(); } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { } } |
<!-- mybatis-config.xml --> <plugins> <plugin interceptor="org.mybatis.example.ExamplePlugin"> <property name="someProperty" value="100"/> </plugin> </plugins> |
上面的插件将会拦截在Executor实例中所有的“update”方法调用,这里的Executor是负责执行低层映射语句的内部对象。
提示:覆盖配置类
除了用插件来修改MyBatis核心行为之外,还可以通过完全覆盖配置类来达到目的。
只需继承后覆盖其中的每个方法,再把它传递到SqlSessionFactoryBuilder.build(myConfig)方法即可。
再次重申,这可能会严重影响MyBatis的行为,请慎重。
转载于:https://www.cnblogs.com/arrows/p/10342099.html
最后
以上就是花痴花瓣为你收集整理的MyBatis配置项--插件(plugins)的全部内容,希望文章能够帮你解决MyBatis配置项--插件(plugins)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复