作用

官方说明:

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

 

posted on 2018-05-31 23:17  刘fighting  阅读(1963)  评论(2编辑  收藏  举报