日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
MyBatis插件原理分析,看完感覺自己better了

本文主要內(nèi)容:

 

大多數(shù)框架都支持插件,用戶可通過編寫插件來自行擴(kuò)展功能,Mybatis也不例外。

在Mybatis中最出名的就是PageHelper 分頁插件,下面我們先來使用一下這個(gè)分頁插件。

如何集成分頁插件

Spring-Boot+Mybatis+PageHelper 。

引入pom依賴

 
 
 
 
  1.  
  2.    com.github.pagehelper 
  3.    pagehelper-spring-boot-starter 
  4.    1.2.3 
  5.  

配置分頁插件配置項(xiàng)

 
 
 
 
  1. pagehelper: 
  2.   helperDialect: mysql 
  3.   reasonable: true 
  4.   supportMethodsArguments: true 
  5.   params: count=countSql 

service接口代碼中

 
 
 
 
  1. PageInfo selectUsersByName(int pageIndex, int pageSize); 

service實(shí)現(xiàn)類代碼中

 
 
 
 
  1. @Override 
  2. public PageInfo selectUsersByName(int pageIndex, int pageSize) { 
  3.     PageHelper.startPage(pageIndex, pageSize); 
  4.     List users = userMapper.selectUsersByName(null); 
  5.     return new PageInfo(users); 

Mapper代碼代碼

 
 
 
 
  1.  
  2.     select * from m_user 
  3.      
  4.          
  5.             `name` = #{userName} 
  6.          
  7.      
  8.  
 
 
 
 
  1. List selectUsersByName(@Param("userName") String userName); 

controller中代碼

 
 
 
 
  1. @GetMapping("/user/name") 
  2. public PageInfo selectUsersByName(int pageIndex, int pageSize) { 
  3.     return userService.selectUsersByName(pageIndex, pageSize); 

然后我們?cè)L問

http://localhost:9002/user/name?pageIndex=1&pageSize=10

輸出結(jié)果:

 

輸出重要項(xiàng)說明:

  • pageNum:當(dāng)前頁碼。
  • pageSize:每頁數(shù)。
  • list:就是我們返回的業(yè)務(wù)數(shù)據(jù)。
  • total:總數(shù)據(jù)。
  • hasNextPage:是否存在下一頁。

我們?cè)诳纯摧敵鯯QL:

 

發(fā)現(xiàn)其實(shí)執(zhí)行了兩條SQL:count和limit。

猜測(cè)分頁插件實(shí)現(xiàn)

1.這個(gè)分頁插件無非就是在我們的查詢條件上拼接了個(gè)limit和做了一個(gè)count查詢。

2.我們這里使用的是Mysql作為數(shù)據(jù)庫,如果是Oracle的話那就不是limit了,所以這里有多重?cái)?shù)據(jù)庫對(duì)應(yīng)的方案。

3.在沒有此插件的前面攔截并做了sql和相關(guān)處理。

根據(jù)官網(wǎng)快速入門插件

下面是來自官網(wǎng)的一段話:

MyBatis 允許你在映射語句執(zhí)行過程中的某一點(diǎn)進(jìn)行攔截調(diào)用。默認(rèn)情況下,MyBatis 允許使用插件來攔截的方法調(diào)用包括:

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

這些類中方法的細(xì)節(jié)可以通過查看每個(gè)方法的簽名來發(fā)現(xiàn),或者直接查看 MyBatis 發(fā)行包中的源代碼。如果你想做的不僅僅是監(jiān)控方法的調(diào)用,那么你最好相當(dāng)了解要重寫的方法的行為。因?yàn)樵谠噲D修改或重寫已有方法的行為時(shí),很可能會(huì)破壞 MyBatis 的核心模塊。這些都是更底層的類和方法,所以使用插件的時(shí)候要特別當(dāng)心。

通過 MyBatis 提供的強(qiáng)大機(jī)制,使用插件是非常簡(jiǎn)單的,只需實(shí)現(xiàn) Interceptor 接口,并指定想要攔截的方法簽名即可。

那我們就嘗試著按照官方來寫一個(gè)插件。

自定義插件

 
 
 
 
  1. @Intercepts({@Signature( 
  2.         type= Executor.class, 
  3.         method = "update", 
  4.         args = {MappedStatement.class,Object.class})}) 
  5. public class TianPlugin implements Interceptor { 
  6.     private Properties properties = new Properties(); 
  7.  
  8.     @Override 
  9.     public Object intercept(Invocation invocation) throws Throwable { 
  10.         System.out.println("老田寫的一個(gè)Mybatis插件--start"); 
  11.         Object returnObject = invocation.proceed(); 
  12.         System.out.println("老田寫的一個(gè)Mybatis插件---end"); 
  13.         return returnObject; 
  14.     } 

然后把插件類注入到容器中。

 

這里的自定義完全是官網(wǎng)給出的案例。從自定義的插件類中看到有個(gè)update,我們猜測(cè)肯定是需要執(zhí)行update才會(huì)被攔截到。

訪問前面的代碼:http://localhost:9002/updateUser

 

成功了。

這是大家肯定會(huì)聯(lián)想到我們剛剛開始學(xué)動(dòng)態(tài)代理的時(shí)候,不就是在要調(diào)用的方法的前面和后面做點(diǎn)小東東嗎?

Mybatis的插件確實(shí)就是這樣的。

我們來分析一下官方的那段話和我們自定義的插件。

分析

首先,我們自定義的插件必須是針對(duì)下面這四個(gè)類以及方法。

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

其次,我們必須實(shí)現(xiàn)Mybatis的Interceptor。

 

Interceptor中三個(gè)方法的作用:

  • intercept():執(zhí)行攔截內(nèi)容的地方,比如:在調(diào)用某類方法前后做一些自己的處理,簡(jiǎn)單就是打印日志。
  • plugin():決定是否觸發(fā)intercept()方法。
  • setProperties():給自定義的攔截器傳遞我們配置的屬性參數(shù)(這個(gè)可以暫時(shí)不管他,后面我們寫一個(gè)相對(duì)完整點(diǎn)的插件,你就明白是干啥的了)。

plugin方法

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

默認(rèn)實(shí)現(xiàn)方法,里面調(diào)用了Plugin.wrap()方法。

 
 
 
 
  1. public class Plugin implements InvocationHandler { 
  2.  
  3.   private Object target; 
  4.   private Interceptor interceptor; 
  5.   private Map, Set> signatureMap; 
  6.  
  7.   private Plugin(Object target, Interceptor interceptor, Map, Set> signatureMap) { 
  8.     this.target = target; 
  9.     this.interceptor = interceptor; 
  10.     this.signatureMap = signatureMap; 
  11.   } 
  12.  
  13.   public static Object wrap(Object target, Interceptor interceptor) { 
  14.     Map, Set> signatureMap = getSignatureMap(interceptor); 
  15.     Class type = target.getClass(); 
  16.     Class[] interfaces = getAllInterfaces(type, signatureMap); 
  17.     if (interfaces.length > 0) { 
  18.       // 創(chuàng)建JDK動(dòng)態(tài)代理對(duì)象 
  19.       return Proxy.newProxyInstance( 
  20.           type.getClassLoader(), 
  21.           interfaces, 
  22.           new Plugin(target, interceptor, signatureMap)); 
  23.     } 
  24.     return target; 
  25.   } 
  26.  
  27.   @Override 
  28.   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
  29.     try { 
  30.       Set methods = signatureMap.get(method.getDeclaringClass()); 
  31.       // 判斷是否是需要攔截的方法(很重要) 
  32.       if (methods != null && methods.contains(method)) { 
  33.         // 回調(diào)intercept()方法 
  34.         return interceptor.intercept(new Invocation(target, method, args)); 
  35.       } 
  36.       return method.invoke(target, args); 
  37.     } catch (Exception e) { 
  38.       throw ExceptionUtil.unwrapThrowable(e); 
  39.     } 
  40.   } 
  41. //...省略其他不相關(guān)代碼 

這不就是一個(gè)JDK動(dòng)態(tài)代理嗎?

Map

所以,我們不要?jiǎng)硬粍?dòng)就說反射性能很差,那是因?yàn)槟銢]有像Mybatis一樣去緩存一個(gè)對(duì)象的反射結(jié)果。

判斷是否是需要攔截的方法,這句注釋很重要,一旦忽略了,都不知道Mybatis是怎么判斷是否執(zhí)行攔截內(nèi)容的,要記住。

Plugin.wrap(target, this)是干什么的?

使用JDK的動(dòng)態(tài)代理,給target對(duì)象創(chuàng)建一個(gè)delegate代理對(duì)象,以此來實(shí)現(xiàn)方法攔截和增強(qiáng)功能,它會(huì)回調(diào)intercept()方法。

為什么要寫注解?注解都是什么含義?

在我們自定義的插件上有一堆注解,別害怕。

Mybatis規(guī)定插件必須編寫Annotation注解,是必須,而不是可選。

 
 
 
 
  1. @Intercepts({@Signature( type= Executor.class, method = "update", 
  2.                         args = {MappedStatement.class,Object.class})} 
  3.            ) 
  4. public class TianPlugin implements Interceptor { 

@Intercepts注解:裝載一個(gè)@Signature列表,一個(gè)@Signature其實(shí)就是一個(gè)需要攔截的方法封裝。那么,一個(gè)攔截器要攔截多個(gè)方法,自然就是一個(gè)@Signature列表。

 
 
 
 
  1. type= Executor.class, method = "update",args = {MappedStatement.class,Object.class} 

解釋:要攔截Executor接口內(nèi)的query()方法,參數(shù)類型為args列表。

 

那如果想攔截多個(gè)方法呢?

 
 
 
 
  1. @Documented 
  2. @Retention(RetentionPolicy.RUNTIME) 
  3. @Target(ElementType.TYPE) 
  4. public @interface Intercepts { 
  5.   Signature[] value(); 

這就簡(jiǎn)單了吧,我們?cè)贎Intercepts注解中可以存放多個(gè)@Signature注解。

比如說前面分頁插件中就是攔截多個(gè)方法的。

 

為什么攔截兩個(gè)都是query方法呢?因?yàn)樵贓xecutor中有兩個(gè)query方法。

 

總結(jié)下:

Mybatis規(guī)定必須使用@Intercepts注解。

@Intercepts注解內(nèi)可以添加多個(gè)類多個(gè)方法,注意方法名和參數(shù)類型個(gè)數(shù)一定要對(duì)應(yīng)起來。

本文轉(zhuǎn)載自微信公眾號(hào)「 Java后端技術(shù)全?!?,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系 Java后端技術(shù)全棧公眾號(hào)。


網(wǎng)站欄目:MyBatis插件原理分析,看完感覺自己better了
網(wǎng)站URL:http://www.5511xx.com/article/dpehhes.html