详解MyBatis自定义Plugin插件

时间:2019-04-15
本文章向大家介绍详解MyBatis自定义Plugin插件,主要包括详解MyBatis自定义Plugin插件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

作用

官方说明:

MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。

什么意思呢?就是你可以对执行某些方法之前进行拦截,做自己的一些操作,如:

1.记录所有执行的SQL(通过对 MyBatis org.apache.ibatis.executor.statement.StatementHandler 中的prepare 方法进行拦截)

2.修改SQL(org.apache.ibatis.executor.Executor中query方法进行拦截)等。

但拦截的方法调用有限制,MyBatis 允许使用插件来拦截的方法调用包括:

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

实现

使用插件是非常简单的,只需实现 Interceptor 接口,并指定想要拦截的方法签名即可。

// ExamplePlugin.java
@Intercepts({@Signature(
 type= Executor.class,
 method = "update",
 args = {MappedStatement.class,Object.class},
 @Signature(
  type = Executor.class, //必须为上面所支持的类
  method = "query", //类中支持的方法,可从源码中查看支持哪些方法
  args = {MappedStatement.class, Object.class , RowBounds.class, ResultHandler.class})}) //对应的参数Class,也可从源码中查看
public class ExamplePlugin implements Interceptor {
 public Object intercept(Invocation invocation) throws Throwable {
 Object[] queryArgs = invocation.getArgs();
  MappedStatement mappedStatement = (MappedStatement) queryArgs[0];
  Object parameter = queryArgs[1];
  BoundSql boundSql = mappedStatement.getBoundSql(parameter);
  String sql = boundSql.getSql();//获取到SQL ,可以进行调整
  String name = invocation.getMethod().getName();
  queryArgs[1] = 2; //可以修改参数内容
  System.err.println("拦截的方法名是:" + name);
  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>

当我们调用query方法时,匹配拦截器的方法, 所以会执行拦截器下intercept方法,做自己的处理。

参考资料,官网

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

总结

以上所述是小编给大家介绍的MyBatis自定义Plugin插件,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!