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)

大家都在看

  • Spring Boot 整合Hibernate Validator

    Spring Boot 整合Hibernate Validator 代码仓库: https://github.com/Rain-with-me/JavaStudyCode/tree…

    数据库 2023年6月14日
    092
  • html简单学习!

    博主学习html的随记 1.常用标签 1.基础标签 2.格式标签 3.表单 4.超文本标签 5.列表 6.表格 7.样式 8.特殊符号 9.内联框架(网页嵌套) 1.常用标签 1….

    数据库 2023年6月16日
    081
  • 用Python做一个中秋抢购月饼的脚本

    ; 序言 每逢佳节倍思亲,想买个东西给家里,结果发现手速不够,网速不够快,没有时间下单等等各种原因导致最后想买的东西售罄了… 甚至跟你一起抢购的可能是脚本,太真实了! …

    数据库 2023年6月14日
    090
  • Java面向对象(上)

    Java面向对象(上) 一、面向对象的思想 1、面向过程: 面向过程就是分析出解决问题所需要的步骤,然后用函数把这些步骤逐一实现,使用的时候依次调用就可以了。 2、面向对象: 面向…

    数据库 2023年6月11日
    090
  • MySQL8.0 DDL原子性特性

    1. DDL原子性概述 8.0之前并没有统一的数据字典dd,server层和引擎层各有一套元数据,sever层的元数据包括(.frm,.opt,.par,.trg等),用于存储表定…

    数据库 2023年6月9日
    055
  • 使用JMeter进行MySQL的压力测试

    GreatSQL社区原创内容未经授权不得随意使用,转载请联系小编并注明来源。 GreatSQL是MySQL的国产分支版本,使用上与MySQL一致。 前言 1. JMeter安装 2…

    数据库 2023年5月24日
    089
  • 时序数据库InfluxDB的基本语法

    一 了解InfluxDB的必要性 Time series data is a series of data points each associated with a specif…

    数据库 2023年6月16日
    084
  • SpringBoot自动装配-自定义Start

    SpringBoot自动装配 JAVA技术交流群:737698533 SpringBootApplication注解 什么是自动装配,也就是说帮你把需要的类自动添加到Spring容…

    数据库 2023年6月16日
    082
  • MySQL在Linux环境下的安装、初始化、配置

    CentOS操作系统,可选择: MySQL Community Server 8.0.28 Red Hat Enterprise Linux / Oracle Linux Red …

    数据库 2023年5月24日
    083
  • MySQL45讲之IO性能提升

    本文介绍 MySQL 的 binlog 和 redo log 写入机制和刷盘策略,以及如何提升 MySQL 的 IO 性能。 binlog 的写入机制 binlog 的写入流程是:…

    数据库 2023年5月24日
    069
  • 多商户商城系统功能拆解30讲-平台端营销-商家优惠券

    多商户商城系统,也称为B2B2C(BBC)平台电商模式多商家商城系统。可以快速帮助企业搭建类似拼多多/京东/天猫/淘宝的综合商城。 多商户商城系统支持商家入驻加盟,同时满足平台自营…

    数据库 2023年6月14日
    083
  • Mysql8+数据库安装和使用

    一、Mysql的版本选择 Mysql目前分文社区版和企业版,社区版在技术方面会加入许多新的未经严格测试的特性,而企业版经过严格测试认证,更加稳定、安全、可靠,性能也比社区版好。社区…

    数据库 2023年6月14日
    076
  • 源码安装Nginx以及用systemctl管理

    一、源码安装Nginx: 下载 nginx软件包 进入nginx-1.20.1目录 安装依赖 /configure软件检查( ./configure–prefix=/u…

    数据库 2023年6月14日
    081
  • MySQL实战45讲 4,5

    04 | 深入浅出索引(上) 索引的出现其实就是为了提高数据查询的效率,就像书的目录一样 索引的常见模型 哈希表、有序数组和搜索树 哈希表 User2 和 User4 根据身份证号…

    数据库 2023年6月16日
    098
  • Spring Boot启动流程

    Spring Boot启动流程 君生我未生,君生我已老。君恨我生迟,我恨君生早。 一、简述 Spring Boot启动流程分析使用版本SpringBoot VERSION:版本 2…

    数据库 2023年6月14日
    089
  • jdbc-使用工具类

    package com.cqust; import com.cqust.utils.JDBCUtil; import java.sql.Connection;import java…

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