栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

详解MyBatis自定义Plugin插件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

在配置文件中注册插件



 
  
 

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

参考资料,官网

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

总结

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140778.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号