MyBatis7:MyBatis外掛程式及樣本----列印每條SQL語句及其執行時間,mybatis7mybatis

來源:互聯網
上載者:User

MyBatis7:MyBatis外掛程式及樣本----列印每條SQL語句及其執行時間,mybatis7mybatis

Plugins

摘一段來自MyBatis官方文檔的文字。

MyBatis允許你在某一點攔截已映射語句執行的調用。預設情況下,MyBatis允許使用外掛程式來攔截方法調用

  • Executor(update、query、flushStatements、commint、rollback、getTransaction、close、isClosed)
  • ParameterHandler(getParameterObject、setParameters)
  • ResultSetHandler(handleResultSets、handleOutputParameters)
  • StatementHandler(prepare、parameterize、batch、update、query)

這些類中方法的詳情可以通過查看每個方法的簽名來發現,而且它們的原始碼存在於MyBatis發行包中。你應該理解你所覆蓋方法的行為,假設你所做的要比監視調用要多。如果你嘗試修改或覆蓋一個給定的方法,你可能會打破MyBatis的核心。這是低層次的類和方法,要謹慎使用外掛程式。

 

外掛程式樣本:列印每條SQL語句及其執行時間

以下通過代碼來示範一下如何使用MyBatis的外掛程式,要示範的情境是:列印每條真正執行的SQL語句及其執行的時間。這是一個非常有用的需求,MyBatis本身的日誌可以記錄SQL,但是有以下幾個問題:

寫MyBatis外掛程式非常簡單,只需要實現Interceptor介面即可,我這裡將我的Interceptor命名為SqlCostInterceptor:

  1 /**  2  * Sql執行時間記錄攔截器   3  */  4 @Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),  5     @Signature(type = StatementHandler.class, method = "update", args = {Statement.class})})  6 public class SqlCostInterceptor implements Interceptor {  7   8     @Override  9     public Object intercept(Invocation invocation) throws Throwable { 10         Object target = invocation.getTarget(); 11         if (target instanceof StatementHandler) { 12             long startTime = System.currentTimeMillis(); 13             StatementHandler statementHandler = (StatementHandler) target; 14             try { 15                 return invocation.proceed(); 16             } finally { 17                 long endTime = System.currentTimeMillis(); 18                 long sqlCost = endTime - startTime; 19                  20                 BoundSql boundSql = statementHandler.getBoundSql(); 21                 String sql = boundSql.getSql(); 22                 Object parameterObject = boundSql.getParameterObject(); 23                 List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings(); 24                  25                 // 格式化Sql語句,去除分行符號,替換參數 26                 sql = formatSql(sql, parameterObject, parameterMappingList); 27                  28                 System.out.println("SQL:[" + sql + "]執行耗時[" + sqlCost + "ms]"); 29             } 30         } 31          32         return invocation.proceed(); 33     } 34  35     @Override 36     public Object plugin(Object target) { 37         return Plugin.wrap(target, this); 38     } 39  40     @Override 41     public void setProperties(Properties properties) { 42          43     } 44      45     @SuppressWarnings("unchecked") 46     private String formatSql(String sql, Object parameterObject, List<ParameterMapping> parameterMappingList) { 47         sql = sql.replace("\n", "").replace("\t", "").replace("  ", " ").replace("( ", "(").replace(" )", ")"); 48         // 出異常時返回沒有替換過預留位置的sql 49         String sqlWithoutReplacePlaceholder = sql; 50          51         try { 52             if (parameterMappingList != null) { 53                 Class<?> parameterObjectClass = parameterObject.getClass(); 54  55                 if (isMap(parameterObjectClass)) { 56                     Map<String, Object> paramMap = (Map<String, Object>) parameterObject; 57                     for (ParameterMapping parameterMapping : parameterMappingList) { 58                         String propertyName = parameterMapping.getProperty(); 59                         Object propertyValue = paramMap.get(propertyName); 60                         if (propertyValue != null) { 61                             if (propertyValue.getClass().isAssignableFrom(String.class)) { 62                                 propertyValue = "\"" + propertyValue + "\""; 63                             } 64  65                             sql = sql.replaceFirst("\\?", propertyValue.toString()); 66                         } 67                     } 68                 } else { 69                     for (ParameterMapping parameterMapping : parameterMappingList) { 70                         String propertyName = parameterObjectClass.isPrimitive() ? "value" 71                                 : parameterMapping.getProperty(); 72                         Field field = parameterObjectClass.getDeclaredField(propertyName); 73                         field.setAccessible(true); 74                         String propertyValue = String.valueOf(field.get(parameterObject)); 75                         if (propertyValue.getClass().isAssignableFrom(String.class)) { 76                             propertyValue = "\"" + propertyValue + "\""; 77                         } 78  79                         sql = sql.replaceFirst("\\?", propertyValue); 80                     } 81                 } 82             }  83         } catch (Exception e) { 84             return sqlWithoutReplacePlaceholder; 85         } 86          87         return sql; 88     } 89      90     private boolean isMap(Class<?> parameterObjectClass) { 91         Class<?>[] classes = parameterObjectClass.getInterfaces(); 92         for (Class<?> clazz : classes) { 93             if (clazz.isAssignableFrom(Map.class)) { 94                 return true; 95             } 96         } 97          98         return false; 99     }100     101 }

分析一下這段代碼。

首先是註解@Intercepts與@Signature,這兩個註解是必須的,因為Plugin的wrap方法會取這兩個註解裡面參數。@Intercepts中可以定義多個@Signature,一個@Signature表示符合如下條件的方法才會被攔截:

  • 介面必須是type定義的類型
  • 方法名必須和method一致
  • 方法形參的Class類型必須和args定義Class類型順序一致

接著的一個問題是:有四個介面可以攔截,為什麼使用StatementHandler去攔截?根據名字來看ParameterHandler和ResultSetHandler,前者處理參數,後者處理結果是不可能使用的,剩下的就是Executor和StatementHandler了。攔截StatementHandler的原因是而不是用Executor的原因是:

  • Executor的update與query方法可能用到MyBatis的一二級緩衝從而導致統計的並不是真正的SQL執行時間
  • StatementHandler的update與query方法無論如何都會統計到PreparedStatement的execute方法執行時間,儘管也有一定誤差(誤差主要來自會將處理結果的時間也算上),但是相差不大

接著講一下setProperties方法,可以將一些配置屬性配置在<plugin></plugin>的子標籤<property />中,所有的配置屬性會在形參Properties中,setProperties方法可以拿到配置的屬性進行需要的處理。

接著講一下plugin方法,這裡是為目標介面組建代理程式,不需要也沒必要自己去寫組建代理程式的方法,MyBatis的Plugin類已經為我們提供了wrap方法(當然如果自己有自己的邏輯也可以在Plugin.wrap方法前後加入,但是最終一定要使用Plugin.wrap方法組建代理程式),看一下該方法的實現:

 1 public static Object wrap(Object target, Interceptor interceptor) { 2     Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor); 3     Class<?> type = target.getClass(); 4     Class<?>[] interfaces = getAllInterfaces(type, signatureMap); 5     if (interfaces.length > 0) { 6       return Proxy.newProxyInstance( 7           type.getClassLoader(), 8           interfaces, 9           new Plugin(target, interceptor, signatureMap));10     }11     return target;12 }

因為這裡的target一定是一個介面,因此可以放心使用JDK本身提供的Proxy類,這裡相當於就是如果該介面滿足方法簽名那麼就為之產生一個代理。

最後就是intercept方法了,這裡就是攔截器的核心代碼了,方法的邏輯我就不解釋了,可以自己看一下,唯一要注意的一點就是無論如何最終一定要返回invocation.proceed(),保證攔截器的層層調用。

 

xml檔案配置即效果示範

寫完了外掛程式,只需要在config.xml檔案中進行一次配置即可,非常簡單:

 1 <plugins> 2     <plugin interceptor="org.xrq.mybatis.plugin.SqlCostInterceptor" /> 3 </plugins>

這裡每個<plugin>子標籤代表一個外掛程式,interceptor表示攔截器的完整路徑,每個人的不同。

有了類和這段配置,就可以使用SqlCostInterceptor了,SqlCostInterceptor是通用的,但是每個人的CRUD是不同的,我列印一下我這裡CRUD執行的結果:

SQL:[insert into mail(id, create_time, modify_time, web_id, mail, use_for) values(null, now(), now(), "1", "123@sina.com", "個人使用");]執行耗時[1ms]SQL:[insert into mail(id, create_time, modify_time, web_id, mail, use_for) values(null, now(), now(), "2", "123@qq.com", "企業使用");]執行耗時[1ms]SQL:[insert into mail(id, create_time, modify_time, web_id, mail, use_for) values(null, now(), now(), "3", "123@sohu.com", "註冊帳號使用");]執行耗時[0ms]

看到列印了完整的SQl語句以及SQL語句執行時間。

不過要說明一點,這個外掛程式只是一個簡單的Demo,我並沒有完整測試過,應該是無法覆蓋所有情境的,所以如果想用這段程式碼片段列印真正的SQL及其執行時間的朋友,還需要在這個基礎上做修改,不過即使不改代碼,這個外掛程式起到美化SQL的作用,去除一些分行符號還是沒問題的。

至於MyBatis外掛程式的實現原理,會在我【MyBatis源碼分析】系列文章中詳細解讀。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.