热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

详解MyBatis自定义Plugin插件

这篇文章主要介绍了MyBatis自定义Plugin插件的相关知识,实现方法也很简单,只需实现Interceptor接口,并指定想要拦截的方法签名即可,需要的朋友可以参考下

作用

官方说明:

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) {
 }
}

在配置文件中注册插件



 
  
 

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

参考资料,官网

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

总结

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


推荐阅读
author-avatar
PHPSM
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有