Mybatis插件开发原理

Mybatis插件说明

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

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

这些类中方法的细节可以通过查看每个方法的签名来发现,或者直接查看 MyBatis 的发行包中的源代码。 假设你想做的不仅仅是监控方法的调用,那么你应该很好的了解正在重写的方法的行为。 因为如果在试图修改或重写已有方法的行为的时候,你很可能在破坏 MyBatis 的核心模块。 这些都是更低层的类和方法,所以使用插件的时候要特别当心。

通过 MyBatis 提供的强大机制,使用插件是非常简单的,只需实现 Interceptor 接口,并指定了想要拦截的方法签名即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 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) {
}
}

@Intercepts注解表明该类是拦截器,参数是方法签名数组。

@Signature注解是方法签名参数分别是:

  • type,表示要拦截的接口类型
  • method,表示拦截接口下的方法
  • args,表示方法参数

主要在intercept方法中编写插件逻辑,通过该方法的参数invocation,可以获取调用的方法名和参数对象。

plugin方法主要是对目标对象的包装。

setProperties方法会读取mybatis-config.xml插件配置中设置的属性。

1
2
3
4
5
6
<!-- mybatis-config.xml -->
<plugins>
<plugin interceptor="org.mybatis.example.ExamplePlugin">
<property name="someProperty" value="100"/>
</plugin>
</plugins>

上面的插件将会拦截在 Executor 实例中所有的 “update” 方法调用, 这里的 Executor 是负责执行低层映射语句的内部对象。

推荐一款动态添加日期的插件

dynamic-add-date

是基于Mybatis插件原理开发的可以动态在InsertUpdate Sql语句中添加日期列和对应的值的插件,并且支持批量插入和批量更新。

详细介绍可以进入以上链接。

参考

http://www.mybatis.org/mybatis-3/zh/configuration.html#plugins

以上,如有问题欢迎提出!

如果对您有所帮助,欢迎投食!
0%