mybatis 攔截器

来源:https://www.cnblogs.com/monianxd/archive/2022/07/15/16480643.html
-Advertisement-
Play Games

1.mybatis攔截器介紹 攔截器可在mybatis進行sql底層處理的時候執行額外的邏輯,最常見的就是分頁邏輯、對結果集進行處理過濾敏感信息等。 public ParameterHandler newParameterHandler(MappedStatement mappedStatement ...


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<>();

  // 遍歷定義的攔截器,對攔截的對象進行包裝
  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
  }

}

mybatis攔截器本質上使用了jdk動態代理,interceptorChain攔截器鏈中存儲了用戶定義的攔截器,會遍歷進行對目標對象代理包裝。

用戶自定義攔截器類需要實現Interceptor介面,以及實現intercept方法,plugin和setProperties方法可重寫,plugin方法一般不會改動,該方法調用了Plugin的靜態方法wrap實現了對目標對象的代理

public class Plugin implements InvocationHandler {

  // 攔截目標對象
  private final Object target;

  // 攔截器對象-執行邏輯
  private final Interceptor interceptor;

  // 攔截介面和攔截方法的映射
  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;
  }

  // 獲取jdk代理對象
  public static Object wrap(Object target, Interceptor interceptor) {
    // 存儲攔截介面和攔截方法的映射
    Map<Class<?>, Set<Method>> 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;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      // 獲取需要攔截的方法集合,若不存在則使用目標對象執行
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
        // Invocation存儲了目標對象、攔截方法以及方法參數
        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) {
    // 獲取Intercepts註解值不能為空
    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 攔截的類型
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
    for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
      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;
  }

  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()]);
  }

}
@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結果轉駝峰
 */
@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 {
    // 調用目標方法
    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);
      }
    }
  }

  // 下劃線轉駝峰
  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();
  }
}

這個例子攔截的是ResultSetHandler的handleResultSets方法,這個方法是用來對結果集處理的,看intercept方法首先調用了目標對象的方法接著強轉為List<Object>類型,這裡為什麼可以強轉呢,因為我們可以看到handleResultSets方法定義<E> List<E> handleResultSets(Statement stmt) throws SQLException; 返回的是List類型,然後遍歷列表,若元素是map類型的再進行處理把key值轉化為駝峰形式重新put到map中。

最後不要忘了把自定義的攔截器添加到配置中,這邊是使用xml配置的,添加完後接著運行測試代碼,可以看到列user_id已經轉換成駝峰形式了。

<plugins>
  <plugin interceptor="org.apache.ibatis.study.interceptor.MyInterceptor">
  </plugin>
</plugins>
#mapper介面
List<Map> selectAllUsers();

#mapper.xml
<select id="selectAllUsers" resultType="map">
    select user_id, username, password, nickname
    from user
</select>
  
      
#java測試類
public class Test {

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

    try (InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml")) {
      // 構建session工廠 DefaultSqlSessionFactory
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      SqlSession sqlSession = sqlSessionFactory.openSession();
      UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      System.out.println(userMapper.selectAllUsers());
    }
  }

}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.String是基本數據類型麽?不是基本數據類型,byte int char long flout duable boolem short 2.int 和integer區別int是基本數據類型,integer 是一個包裝類 3..JAVA中幾種集合(List、Set和Map)的區別?list 和s ...
  • 目錄導航 分支控制 - if.....else 單分支 if 雙分支 if....else 多分支 if....else if.....else switch - 分支控制 switch (表達式){case 常量1: 語句1; breack:} -- 語法 breack 退出當語句,如果沒有bra ...
  • likeshop單商戶開源商城系統,公眾號商城、H5商城、微信小程式商城、抖音小程式商城、位元組小程式商城、頭條小程式商城、安卓APP商城、蘋果APP商城代碼全開源,免費商用。 適用場景 系統適用於B2C,單商戶,自營商城場景。完美契合私域流量變現閉環交易使用。 系統亮點 LikeShop在電商通用組 ...
  • 一、前言 在項目中有需要對word進行操作的,可以看看哈,本次使用比較強大的spire組件來對word進行操作,免費版支持三頁哦,對於不止三頁的word文件,可以購買收費版,官網:https://www.e-iceblue.cn/tutorials.html#,也可使用其他組件實現,如poi、doc ...
  • MongoDB聚合查詢 什麼是聚合查詢 聚合操作主要用於處理數據並返回計算結果。聚合操作將來自多個文檔的值組合在一起,按條件分組後,再進行一系列操作(如求和、平均值、最大值、最小值)以返回單個結果。 MongoDB的聚合查詢 ​ 聚合是MongoDB的高級查詢語言,它允許我們通過轉化合併由多個文檔的 ...
  • 一、字元串 1、字元串編碼發展: 1)ASCII碼: 一個位元組去表示 (8個比特(bit)作為一個位元組(byte),因此,一個位元組能表示的最大的整數就是255(二進位11111111 = 十進位255)) 2)Unicode:兩個位元組表示(將各國的語言(中文編到GB2312,日文編到Shift_JI ...
  • JetBrAIns RubyMine 2022 for Mac是應用在Mac上的一款強大的Ruby代碼編輯器,可以通過可定製的配色方案,鍵盤方案以及高效開發所需的所有外觀設置,智能導航一鍵導航到聲明,超級方法,測試,用法,實現,是一款功能強大的代碼編輯工具。 詳情:JetBrains RubyMin ...
  • 本文主要介紹crudapi三種API認證方式,基於Spring Security框架實現, 包括Cookie,Basic Auth,JWT令牌Token。 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...