如何在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>

以上就是如何在MyBatis中自定义Plugin插件,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。