mybatis 拦截器

1.mybatis拦截器介绍

拦截器可在mybatis进行sql底层处理的时候执行额外的逻辑,最常见的就是分页逻辑、对结果集进行处理过滤敏感信息等。

  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) {
    return newExecutor(transaction, defaultExecutorType);
  }

  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    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);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

从上面的代码可以看到mybatis支持的拦截类型只有四种(按拦截顺序)

1.Executor 执行器接口

2.StatementHandler sql构建处理器

3.ParameterHandler 参数处理器

4.ResultSetHandler 结果集处理器

2.拦截器原理

public class InterceptorChain {

  private final List<interceptor> interceptors = new ArrayList<>();

  // &#x904D;&#x5386;&#x5B9A;&#x4E49;&#x7684;&#x62E6;&#x622A;&#x5668;&#xFF0C;&#x5BF9;&#x62E6;&#x622A;&#x7684;&#x5BF9;&#x8C61;&#x8FDB;&#x884C;&#x5305;&#x88C5;
  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<interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}

#Interceptor
public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;

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

  default void setProperties(Properties properties) {
    // NOP
  }

}</interceptor></interceptor>

mybatis拦截器本质上使用了jdk动态代理,interceptorChain拦截器链中存储了用户定义的拦截器,会遍历进行对目标对象代理包装。

用户自定义拦截器类需要实现Interceptor接口,以及实现intercept方法,plugin和setProperties方法可重写,plugin方法一般不会改动,该方法调用了Plugin的静态方法wrap实现了对目标对象的代理

public class Plugin implements InvocationHandler {

  // &#x62E6;&#x622A;&#x76EE;&#x6807;&#x5BF9;&#x8C61;
  private final Object target;

  // &#x62E6;&#x622A;&#x5668;&#x5BF9;&#x8C61;-&#x6267;&#x884C;&#x903B;&#x8F91;
  private final Interceptor interceptor;

  // &#x62E6;&#x622A;&#x63A5;&#x53E3;&#x548C;&#x62E6;&#x622A;&#x65B9;&#x6CD5;&#x7684;&#x6620;&#x5C04;
  private final Map<class<?>, Set<method>> signatureMap;

  private Plugin(Object target, Interceptor interceptor, Map<class<?>, Set<method>> signatureMap) {
    this.target = target;
    this.interceptor = interceptor;
    this.signatureMap = signatureMap;
  }

  // &#x83B7;&#x53D6;jdk&#x4EE3;&#x7406;&#x5BF9;&#x8C61;
  public static Object wrap(Object target, Interceptor interceptor) {
    // &#x5B58;&#x50A8;&#x62E6;&#x622A;&#x63A5;&#x53E3;&#x548C;&#x62E6;&#x622A;&#x65B9;&#x6CD5;&#x7684;&#x6620;&#x5C04;
    Map<class<?>, Set<method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    // &#x83B7;&#x53D6;&#x62E6;&#x622A;&#x76EE;&#x6807;&#x5BF9;&#x8C61;&#x5B9E;&#x73B0;&#x7684;&#x63A5;&#x53E3;&#xFF0C;&#x82E5;&#x4E3A;&#x7A7A;&#x5219;&#x4E0D;&#x4EE3;&#x7406;
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      // &#x83B7;&#x53D6;&#x9700;&#x8981;&#x62E6;&#x622A;&#x7684;&#x65B9;&#x6CD5;&#x96C6;&#x5408;&#xFF0C;&#x82E5;&#x4E0D;&#x5B58;&#x5728;&#x5219;&#x4F7F;&#x7528;&#x76EE;&#x6807;&#x5BF9;&#x8C61;&#x6267;&#x884C;
      Set<method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
        // Invocation&#x5B58;&#x50A8;&#x4E86;&#x76EE;&#x6807;&#x5BF9;&#x8C61;&#x3001;&#x62E6;&#x622A;&#x65B9;&#x6CD5;&#x4EE5;&#x53CA;&#x65B9;&#x6CD5;&#x53C2;&#x6570;
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }

  private static Map<class<?>, Set<method>> getSignatureMap(Interceptor interceptor) {
    // &#x83B7;&#x53D6;Intercepts&#x6CE8;&#x89E3;&#x503C;&#x4E0D;&#x80FD;&#x4E3A;&#x7A7A;
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
    }
    Signature[] sigs = interceptsAnnotation.value();
    // key &#x62E6;&#x622A;&#x7684;&#x7C7B;&#x578B;
    Map<class<?>, Set<method>> signatureMap = new HashMap<>();
    for (Signature sig : sigs) {
      Set<method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
      try {
        // &#x83B7;&#x53D6;&#x62E6;&#x622A;&#x7684;&#x65B9;&#x6CD5;
        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;
  }

  private static Class<?>[] getAllInterfaces(Class<?> type, Map<class<?>, Set<method>> signatureMap) {
    Set<class<?>> 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()]);
  }

}</class<?></method></class<?></method></method></class<?></method></class<?></method></method></class<?></method></class<?></method></class<?>
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
  /**
   * Returns method signatures to intercept.

   *
   * @return method signatures
   */
  Signature[] value();
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
  /**
   * Returns the java type.

   *
   * @return the java type
   */
  Class<?> type();

  /**
   * Returns the method name.

   *
   * @return the method name
   */
  String method();

  /**
   * Returns java types for method argument.

   * @return java types for method argument
   */
  Class<?>[] args();
}

可以看到,当被拦截的方法被执行时主要调用自定义拦截器的intercept方法,把拦截对象、方法以及方法参数封装成Invocation对象传递过去。

在getSignatureMap方法中可以看到,自定义的拦截器类上需要添加Intercepts注解并且Signature需要有值,Signature注解中的type为需要拦截对象的接口(Executor.class/StatementHandler/ParameterHandler/ResultSetHandler),method为需要拦截的方法的方法名,args为拦截方法的方法参数类型。

3.参考例子

接下来举一个拦截器实现对结果集下划线转驼峰的例子来简要说明

/**
 * @author dxu2
 * @date 2022/7/14
 * map&#x7ED3;&#x679C;&#x8F6C;&#x9A7C;&#x5CF0;
 */
@Intercepts(value = {@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class MyInterceptor implements Interceptor {

  @SuppressWarnings("unchecked")
  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    // &#x8C03;&#x7528;&#x76EE;&#x6807;&#x65B9;&#x6CD5;
    List<object> result = (List<object>) invocation.proceed();
    for (Object o : result) {
      if (o instanceof Map) {
        processMap((Map<string, object>) o);
      } else {
        break;
      }
    }
    return result;
  }

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

  @Override
  public void setProperties(Properties properties) {

  }

  private void processMap(Map<string, object> map) {
    Set<string> keySet = new HashSet<>(map.keySet());
    for (String key : keySet) {
      if ((key.charAt(0) >= 'A' && key.charAt(0) <= 'z') || key.indexof("_")> 0) {
        Object value = map.get(key);
        map.remove(key);
        map.put(camel(key), value);
      }
    }
  }

  // &#x4E0B;&#x5212;&#x7EBF;&#x8F6C;&#x9A7C;&#x5CF0;
  private String camel(String fieldName) {
    StringBuffer stringBuffer = new StringBuffer();
    boolean flag = false;
    for (int i = 0; i < fieldName.length(); i++) {
      if (fieldName.charAt(i) == '_') {
        if (stringBuffer.length() > 0) {
          flag = true;
        }
      } else {
        if (flag) {
          stringBuffer.append(Character.toUpperCase(fieldName.charAt(i)));
          flag = false;
        } else {
          stringBuffer.append(Character.toLowerCase(fieldName.charAt(i)));
        }
      }
    }
    return stringBuffer.toString();
  }
}</=></string></string,></string,></object></object>

这个例子拦截的是ResultSetHandler的handleResultSets方法,这个方法是用来对结果集处理的,看intercept方法首先调用了目标对象的方法接着强转为List

最后不要忘了把自定义的拦截器添加到配置中,这边是使用xml配置的,添加完后接着运行测试代码,可以看到列user_id已经转换成驼峰形式了。

<plugins>
  <plugin interceptor="org.apache.ibatis.study.interceptor.MyInterceptor">
  </plugin>
</plugins>
#mapper&#x63A5;&#x53E3;
List<map> selectAllUsers();

#mapper.xml
<select id="selectAllUsers" resulttype="map">
    select user_id, username, password, nickname
    from user
</select>

#java&#x6D4B;&#x8BD5;&#x7C7B;
public class Test {

  public static void main(String[] args) throws IOException {

    try (InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml")) {
      // &#x6784;&#x5EFA;session&#x5DE5;&#x5382; DefaultSqlSessionFactory
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      SqlSession sqlSession = sqlSessionFactory.openSession();
      UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      System.out.println(userMapper.selectAllUsers());
    }
  }

}</map>

mybatis 拦截器

Original: https://www.cnblogs.com/monianxd/p/16480643.html
Author: 默念x
Title: mybatis 拦截器

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/620890/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 基于mybatis的java代码生成存储过程

    1 — — powered by wanglifeng https://www.cnblogs.com/wanglifeng717 2 DROP PROCEDURE IF EX…

    数据库 2023年5月24日
    079
  • Linux下搭建git分布式管理

    VMware 虚拟机中搭建步骤 一、 1.查一下ip 2.和Xshell连接起来 3.看是否连接上 4.这就ok了 5.输入 yum install git yum install…

    数据库 2023年6月6日
    090
  • leetcode 148. Sort List 排序链表(中等)

    给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。 示例 1: 输入:head = [4,2,1,3]输出:[1,2,3,4] 示例 2: 输入:head …

    数据库 2023年6月16日
    081
  • MySQL Server可执行注释

    MySQL Server当前支持如下3种注释风格: 以’# ‘开头的单行注释 以’– ‘开头的单行注释 C语言风格的单行…

    数据库 2023年5月24日
    093
  • 二手车价格预测 | 构建AI模型并部署Web应用 ⛵

    💡 作者:韩信子@ShowMeAI📘 数据分析实战系列:https://www.showmeai.tech/tutorials/40📘 机器学习实战系列:https://www.s…

    数据库 2023年6月14日
    081
  • AspNetCoreapi 使用 Docker + Centos 7部署

    好久没有更新文章了,前段时间写了一系列的文章放到桌面了,想着修修改改,后来系统中勒索病毒了还被公司网络安全的抓到是我电脑,后来装系统文章给装丢了。然后好长一段时间没有写了。 今天记…

    数据库 2023年6月11日
    095
  • LeetCode 27. 移除元素

    给你一个数组nums和一个值val,你需要 原地 移除所有数值等于val的元素,并返回移除后数组的新长度。 不要使用额外的数组空间,你必须仅使用O(1)额外空间并 原地 修改输入数…

    数据库 2023年6月11日
    080
  • Linux 系统安装RocketMQ

    准备工作 1.去官网下载一个安装包 1.解压 unzip rocketmq-all-4.9.0-bin-release.zip -d /download/compress/ 2.进…

    数据库 2023年6月6日
    087
  • 解决:MyBatis-plus多数据源方法上方添加事务,数据源切换失败

    说明:MyBatis-plus配置了多数据源,添加事务后,数据源切换失败了… 一、场景描述 项目当中使用的多数据源,Impl中有个方法:MethodA。 @Servic…

    数据库 2023年6月6日
    086
  • 一次较波折的MySQL调优

    春节假期的一天,阳光明媚,春暖花开,恰逢冬奥会开幕,想着这天一定是生肖吉日,就能顺风顺水了。没想到,我遇到了一位客户,有点波折。 [En] Spring Festival holi…

    数据库 2023年5月24日
    078
  • Shell第一章《变量》

    什么是shell shell-‘壳’ 命令解释器,一种应用程序 shell语言特点 SHELL语言是指UNIX操作系统的命令语言,同时又是该命令语言的解释程…

    数据库 2023年6月14日
    081
  • Linux网络配置

    Linux网络配置 NAT网络配置 查看网络IP和网关 可以在 编辑->虚拟网络编辑器中 查看网络IP和网关 说明:1.什么是IP协议/地址?即”网络之间能相互连…

    数据库 2023年6月16日
    089
  • Springboot打包部署项目

    这里打包的是jar项目,也就是没有webapp目录,通过maven打包插件打包发布到服务器 废话不多少直接开撸废话不多少直接开撸废话不多少直接开撸废话不多少直接开撸废话不多少直接开…

    数据库 2023年6月6日
    084
  • 版本控制gitlab

    版本控制gitlab 版本控制gitlab 什么是版本控制gitlab gitlab部署 什么是版本控制gitlab GitLab 是一个用于仓库管理系统的开源项目,使用Git作为…

    数据库 2023年6月14日
    088
  • MySQL实战45讲 13

    13 | 为什么表数据删掉一半,表文件大小不变? 一个 InnoDB 表包含两部分,即: 表结构定义和 数据。 在 MySQL 8.0 版本以前, 表结构是存在以.frm 为后缀的…

    数据库 2023年6月16日
    0100
  • MySQL增删改

    数据处理之增删改 插入数据(增) 前提:创建一个空表:id,name,hire_data,salary, 方法一:逐一添加数据 [En] method 1: add data on…

    数据库 2023年5月24日
    065
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球