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

详解MyBatis自定义Plugin插件

程序员文章站 2023-12-16 22:14:10
作用 官方说明: mybatis 允许你在已映射语句执行过程中的某一点进行拦截调用。 什么意思呢?就是你可以对执行某些方法之前进行拦截,做自己的一些操作,如: 1....

作用

官方说明:

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方法,做自己的处理。

参考资料,官网

总结

以上所述是小编给大家介绍的mybatis自定义plugin插件,希望对大家有所帮助

上一篇:

下一篇: