iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >MyBatis 拦截器介绍
  • 225
分享到

MyBatis 拦截器介绍

mybatisjavamysql拦截器 2023-09-02 19:09:08 225人浏览 独家记忆
摘要

mybatis 拦截器介绍 MyBatis 提供了一种插件 (plugin) 的功能,虽然叫做插件,但其实这是拦截器功能。那么拦截器拦截 MyBatis 中的哪些内容呢? 我们进入官网看一看: MyBatis 允许你在已映射语句执行过程中的

mybatis 拦截器介绍

MyBatis 提供了一种插件 (plugin) 的功能,虽然叫做插件,但其实这是拦截器功能。那么拦截器拦截 MyBatis 中的哪些内容呢?

我们进入官网看一看:

MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:

  1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  2. ParameterHandler (getParameterObject, setParameters)
  3. ResultSetHandler (handleResultSets, handleOutputParameters)
  4. StatementHandler (prepare, parameterize, batch, update, query)

我们看到了可以拦截 Executor 接口的部分方法,比如 update,query,commit,rollback 等方法,还有其他接口的一些方法等。

总体概括为:

  1. 拦截执行器的方法
  2. 拦截参数的处理
  3. 拦截结果集的处理
  4. 拦截 sql 语法构建的处理

拦截器的使用

拦截器介绍及配置

首先我们看下 MyBatis 拦截器的接口定义:

public interface Interceptor {  Object intercept(Invocation invocation) throws Throwable;  Object plugin(Object target);  void setProperties(Properties properties);}

比较简单,只有 3 个方法。 MyBatis 默认没有一个拦截器接口的实现类,开发者们可以实现符合自己需求的拦截器。

下面的 MyBatis 官网的一个拦截器实例:

@Intercepts({@Signature(  type= Executor.class,  method = "update",  args = {MappedStatement.class,Object.class})})public class ExamplePlugin implements Interceptor {  public Object intercept(Invocation invocation) throws Throwable {    return invocation.proceed();  }  public Object plugin(Object target) {    return Plugin.wrap(target, this);  }  public void setProperties(Properties properties) {  }}

全局 xml 配置:

    

这个拦截器拦截 Executor 接口的 update 方法(其实也就是 SqlSession 的新增,删除,修改操作),所有执行 executor 的 update 方法都会被该拦截器拦截到。

源码分析

下面我们分析一下这段代码背后的源码

首先从源头 -> 配置文件开始分析:

XMLConfigBuilder 解析 MyBatis 全局配置文件的 pluginElement 私有方法:

private void pluginElement(Xnode parent) throws Exception {    if (parent != null) {      for (XNode child : parent.getChildren()) {        String interceptor = child.getStringAttribute("interceptor");        Properties properties = child.getChildrenAsProperties();        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();        interceptorInstance.setProperties(properties);        configuration.addInterceptor(interceptorInstance);      }    }}

具体的解析代码其实比较简单,就不贴了,主要就是通过反射实例化 plugin 节点中的 interceptor 属性表示的类。然后调用全局配置类 Configuration 的 addInterceptor 方法。

public void addInterceptor(Interceptor interceptor) {       interceptorChain.addInterceptor(interceptor);     }

这个 interceptorChain 是 Configuration 的内部属性,类型为 InterceptorChain,也就是一个拦截器链,我们来看下它的定义:

public class InterceptorChain {  private final List interceptors = new ArrayList();  public Object pluginAll(Object target) {    for (Interceptor interceptor : interceptors) {      target = interceptor.plugin(target);    }    return target;  }  public void addInterceptor(Interceptor interceptor) {    interceptors.add(interceptor);  }  public List getInterceptors() {    return Collections.unmodifiableList(interceptors);  }}

现在我们理解了拦截器配置的解析以及拦截器的归属,现在我们回过头看下为何拦截器会拦截这些方法(Executor,ParameterHandler,ResultSetHandler,StatementHandler 的部分方法):

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);    return parameterHandler;}public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,  ResultHandler resultHandler, BoundSql boundSql) {    ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);    return resultSetHandler;}public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);    return statementHandler;}public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {    executorType = executorType == null ? defaultExecutorType : executorType;    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;    Executor executor;    if (ExecutorType.BATCH == executorType) {      executor = new BatchExecutor(this, transaction);    } else if (ExecutorType.REUSE == executorType) {      executor = new ReuseExecutor(this, transaction);    } else {      executor = new SimpleExecutor(this, transaction);    }    if (cacheEnabled) {      executor = new CachingExecutor(executor, autoCommit);    }    executor = (Executor) interceptorChain.pluginAll(executor);    return executor;}

以上 4 个方法都是 Configuration 的方法。这些方法在 MyBatis 的一个操作 (新增,删除,修改,查询) 中都会被执行到,执行的先后顺序是 Executor,ParameterHandler,ResultSetHandler,StatementHandler (其中 ParameterHandler 和 ResultSetHandler 的创建是在创建 StatementHandler [3 个可用的实现类 CallableStatementHandler,PreparedStatementHandler,SimpleStatementHandler] 的时候,其构造函数调用的 [这 3 个实现类的构造函数其实都调用了父类 BaseStatementHandler 的构造函数])。

这 4 个方法实例化了对应的对象之后,都会调用 interceptorChain 的 pluginAll 方法,InterceptorChain 的 pluginAll 刚才已经介绍过了,就是遍历所有的拦截器,然后调用各个拦截器的 plugin 方法。注意:拦截器的 plugin 方法的返回值会直接被赋值给原先的对象

由于可以拦截 StatementHandler,这个接口主要处理 sql 语法的构建,因此比如分页的功能,可以用拦截器实现,只需要在拦截器的 plugin 方法中处理 StatementHandler 接口实现类中的 sql 即可,可使用反射实现。

MyBatis 还提供了 @Intercepts 和 @Signature 关于拦截器的注解。官网的例子就是使用了这 2 个注解,还包括了 Plugin 类的使用:

@Overridepublic Object plugin(Object target) {    return Plugin.wrap(target, this);}

下面我们就分析这 3 个 "新组合" 的源码,首先先看 Plugin 类的 wrap 方法:

public static Object wrap(Object target, Interceptor interceptor) {    Map, Set> signatureMap = getSignatureMap(interceptor);    Class type = target.getClass();    Class[] interfaces = getAllInterfaces(type, signatureMap);    if (interfaces.length > 0) {      return Proxy.newProxyInstance(          type.getClassLoader(),          interfaces,          new Plugin(target, interceptor, signatureMap));    }    return target;}

Plugin 类实现了 InvocationHandler 接口,很明显,我们看到这里返回了一个 jdk 自身提供的动态代理类。我们解剖一下这个方法调用的其他方法:

getSignatureMap 方法:

private static Map, Set> getSignatureMap(Interceptor interceptor) {    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);    if (interceptsAnnotation == null) { // issue #251      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());          }    Signature[] sigs = interceptsAnnotation.value();    Map, Set> signatureMap = new HashMap, Set>();    for (Signature sig : sigs) {      Set methods = signatureMap.get(sig.type());      if (methods == null) {        methods = new HashSet();        signatureMap.put(sig.type(), methods);      }      try {        Method method = sig.type().getMethod(sig.method(), sig.args());        methods.add(method);      } catch (NoSuchMethodException e) {        throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);      }    }    return signatureMap;}

getSignatureMap 方法解释:首先会拿到拦截器这个类的 @Interceptors 注解,然后拿到这个注解的属性 @Signature 注解集合,然后遍历这个集合,遍历的时候拿出 @Signature 注解的 type 属性 (Class 类型),然后根据这个 type 得到带有 method 属性和 args 属性的 Method。由于 @Interceptors 注解的 @Signature 属性是一个属性,所以最终会返回一个以 type 为 key,value 为 Set 的 Map。

@Intercepts({@Signature(  type= Executor.class,  method = "update",  args = {MappedStatement.class,Object.class})})  

比如这个 @Interceptors 注解会返回一个 key 为 Executor,value 为集合 (这个集合只有一个元素,也就是 Method 实例,这个 Method 实例就是 Executor 接口的 update 方法,且这个方法带有 MappedStatement 和 Object 类型的参数)。这个 Method 实例是根据 @Signature 的 method 和 args 属性得到的。如果 args 参数跟 type 类型的 method 方法对应不上,那么将会抛出异常。

getAllInterfaces 方法:

private static Class[] getAllInterfaces(Class type, Map, Set> signatureMap) {    Set> interfaces = new HashSet>();    while (type != null) {      for (Class c : type.getInterfaces()) {        if (signatureMap.containsKey(c)) {          interfaces.add(c);        }      }      type = type.getSuperclass();    }    return interfaces.toArray(new Class[interfaces.size()]);}

getAllInterfaces 方法解释:根据目标实例 target (这个 target 就是之前所说的 MyBatis 拦截器可以拦截的类,Executor,ParameterHandler,ResultSetHandler,StatementHandler) 和它的父类们,返回 signatureMap 中含有 target 实现的接口数组

所以 Plugin 这个类的作用就是根据 @Interceptors 注解,得到这个注解的属性 @Signature 数组,然后根据每个 @Signature 注解的 type,method,args 属性使用反射找到对应的 Method。最终根据调用的 target 对象实现的接口决定是否返回一个代理对象替代原先的 target 对象。

比如 MyBatis 官网的例子,当 Configuration 调用 newExecutor 方法的时候,由于 Executor 接口的 update (MappedStatement ms, Object parameter) 方法被拦截器被截获。因此最终返回的是一个代理类 Plugin,而不是 Executor。这样调用方法的时候,如果是个代理类,那么会执行:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {    try {      Set methods = signatureMap.get(method.getDeclarinGClass());      if (methods != null && methods.contains(method)) {        return interceptor.intercept(new Invocation(target, method, args));      }      return method.invoke(target, args);    } catch (Exception e) {      throw ExceptionUtil.unwrapThrowable(e);    }}

没错,如果找到对应的方法被代理之后,那么会执行 Interceptor 接口的 interceptor 方法。

这个 Invocation 类如下:

public class Invocation {  private Object target;  private Method method;  private Object[] args;  public Invocation(Object target, Method method, Object[] args) {    this.target = target;    this.method = method;    this.args = args;  }  public Object getTarget() {    return target;  }  public Method getMethod() {    return method;  }  public Object[] getArgs() {    return args;  }  public Object proceed() throws InvocationTargetException, IllegalAccessException {    return method.invoke(target, args);  }}

它的 proceed 方法也就是调用原先方法 (不走代理)。

总结

MyBatis 拦截器接口提供的 3 个方法中,plugin 方法用于某些处理器 (Handler) 的构建过程。interceptor 方法用于处理代理类的执行。setProperties 方法用于拦截器属性的设置。

其实 MyBatis 官网提供的使用 @Interceptors 和 @Signature 注解以及 Plugin 类这样处理拦截器的方法,我们不一定要直接这样使用。我们也可以抛弃这 3 个类,直接在 plugin 方法内部根据 target 实例的类型做相应的操作。

总体来说 MyBatis 拦截器还是很简单的,拦截器本身不需要太多的知识点,但是学习拦截器需要对 MyBatis 中的各个接口很熟悉,因为拦截器涉及到了各个接口的知识点。

本文转载自:Http://www.cnblogs.com/fangjian0423/p/mybatis-interceptor.html

来源地址:https://blog.csdn.net/crg18438610577/article/details/130244508

您可能感兴趣的文档:

--结束END--

本文标题: MyBatis 拦截器介绍

本文链接: https://www.lsjlt.com/news/391241.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • MyBatis 拦截器介绍
    MyBatis 拦截器介绍 MyBatis 提供了一种插件 (plugin) 的功能,虽然叫做插件,但其实这是拦截器功能。那么拦截器拦截 MyBatis 中的哪些内容呢? 我们进入官网看一看: MyBatis 允许你在已映射语句执行过程中的...
    99+
    2023-09-02
    mybatis java mysql 拦截器
  • SpringBoot拦截器的使用介绍
    目录定义拦截器实现HandleInterceptor接口继承HandleInterceptorAdapter类实现WebRequestInterceptor接口实现RequestIn...
    99+
    2024-04-02
  • SpringBoot拦截器的配置使用介绍
    目录1. 配置拦截器2. 一个小 Demo1. 自定义拦截器类—LoginInterceptor2. 将拦截器注册到容器中3. 原理分析1. 配置拦截器 具体步骤: 编写...
    99+
    2022-11-13
    SpringBoot拦截器 SpringBoot拦截器的使用
  • SpringMVC超详细介绍自定义拦截器
    目录1.什么是拦截器2.自定义拦截器执行流程图3.自定义拦截器应用实例1.快速入门2.注意事项和细节3.Debug执行流程4.多个拦截器1.多个拦截器执行流程示意图2.应用实例3.主...
    99+
    2024-04-02
  • springboot中过滤器和拦截器的实例介绍
    这篇文章主要讲解了“springboot中过滤器和拦截器的实例介绍”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“springboot中过滤器和拦截器的实例介绍”吧!拦截器与过滤器  在讲Sp...
    99+
    2023-06-20
  • mybatis拦截器怎么使用
    今天小编给大家分享一下mybatis拦截器怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。mybatis实战之拦截器在...
    99+
    2023-07-05
  • mybatis实战之拦截器解读
    目录myBATis实战之拦截器1、使用方法2、需要注意的地方拦截器的执行顺序与常用插件的整合遇到的问题可以提升的点总结mybatis实战之拦截器 在服务的开发过程中,往往存在这样的需求,针对业务,实现对数据库操作语句做统...
    99+
    2023-03-20
    mybatis拦截器 拦截器 mybatis实战
  • MyBatis拦截器的实现原理
    目录前言 1.使用方法2.MyBatis对象的创建3.代理对象的创建3.1 拦截器的获取3.2 代理对象的创建4. 拦截器的执行过程5. 拦截器的执行顺序前言 Mybati...
    99+
    2024-04-02
  • Mybatis拦截器打印sql问题
    目录1.log4j2配置修改2.配置日志开关3.添加拦截器插件4.拦截器逻辑描述4.1 注入开关4.2 获取sql4.2 获取参数4.3 sql替换参数4.4 打印sql4.5打印效...
    99+
    2023-05-13
    Mybatis拦截器打印sql Mybatis拦截器 拦截器打印sql
  • MyBatis Excutor 拦截器的巧妙用法
    这里要讲的巧妙用法是用来实现在拦截器中执行额外 MyBatis 现有方法的用法。并且会提供一个解决拦截Executor时想要修改MappedStatement时解决并发的问题。这里假设一个场景:实现一个拦截器,记录 MyBatis 所有的 ...
    99+
    2023-05-31
    mybatis excutor 拦截器
  • MyBatis拦截器的原理与使用
    目录一、拦截对象和接口实现示例二、拦截器注册的三种方式        1.XML注册  &n...
    99+
    2024-04-02
  • Mybatis拦截器实现自定义需求
    目录前言一、应用场景二、Mybatis实现自定义拦截器2.1、编写拦截器2.2、添加到Mybatis配置2.3、测试2.4、小结三、拦截器接口介绍intercept 方法plugin...
    99+
    2023-05-19
    Mybatis自定义拦截器 Mybatis 拦截器
  • 在springboot中如何给mybatis加拦截器
    目录1、实现Interceptor接口,并添加拦截注解 @Intercepts1.在mybatis中可被拦截的类型有四种(按照拦截顺序)2.各个参数的含义2、在配置文件中添加拦截器(...
    99+
    2024-04-02
  • Mybatis-Plus实现SQL拦截器的示例
    目录起源实现拦截器接口InnerInterceptor修改sql常用的工具类起源 最近公司要做多租户,Mybatis-Plus的多租户插件很好用,但是有一个场景是:字典表或者某些数据...
    99+
    2023-05-19
    Mybatis-Plus SQL拦截器 Mybatis-Plus 拦截器
  • Springboot如何实现自定义mybatis拦截器
    这篇文章将为大家详细讲解有关Springboot如何实现自定义mybatis拦截器,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。实践的准备 : 整合mybatis ,然后故意写了3个查询方法, ...
    99+
    2023-06-22
  • MyBatis拦截器实现分页功能实例
    由于业务关系 巴拉巴拉巴拉好吧 简单来说就是原来的业务是 需要再实现类里写 selectCount 和selectPage两个方法才能实现分页功能现在想要达到效果是 只通过一个方法就可以实现 也就是功能合并 所以就有了下面的实践既然是基于M...
    99+
    2023-05-31
    mybatis 拦截器 分页
  • 使用mybatis拦截器处理敏感字段
    目录mybatis拦截器处理敏感字段前言思路解析代码趟过的坑(敲黑板重点)mybatis Excutor 拦截器的使用这里假设一个场景实现过程的关键步骤和代码重点mybatis拦截器...
    99+
    2024-04-02
  • 利用Mybatis Plus实现一个SQL拦截器
    目录起源实现拦截器接口InnerInterceptor修改sql常用的工具类起源 最近公司要做多租户,Mybatis-Plus的多租户插件很好用,但是有一个场景是:字典表或者某些数据...
    99+
    2023-05-19
    Mybatis Plus实现SQL拦截器 Mybatis Plus SQL拦截 Mybatis Plus SQL
  • mybatis拦截器及不生效如何解决
    这篇“mybatis拦截器及不生效如何解决”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“mybatis拦截器及不生效如何解决...
    99+
    2023-07-05
  • SpringMVC拦截器
    7.SpringMVC拦截器 7.1-SpringMVC拦截器-拦截器的作用(理解) Spring MVC 的拦截器类似于 Servlet 开发中的过滤器 Filter,用于对处理器进行预处理和后处理。 将拦截器按一定的顺序联结成一条链,这...
    99+
    2023-08-19
    java servlet spring
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作