最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Mybatis源碼解析之mapper接口的代理模式詳解

 更新時(shí)間:2023年12月25日 11:47:43   作者:二狗家有礦  
這篇文章主要介紹了Mybatis源碼解析之mapper接口的代理模式詳解,在mybatis中執(zhí)行sql時(shí)有兩種方式,一種是基于statementId,也就是直接調(diào)用SqlSession的方法,需要的朋友可以參考下

一、簡(jiǎn)介

在mybatis中執(zhí)行sql時(shí)有兩種方式,一種是基于statementId,也就是直接調(diào)用SqlSession的方法,如sqlSession.update(“statementId”); 還有一種方法是基于java接口,也是日常開發(fā)中最常用的方式。 mapper接口中的每個(gè)方法都可以喝mapper xml中的一條sql語句對(duì)應(yīng),我們可以直接通過調(diào)用接口方法的方式進(jìn)行sql執(zhí)行。因?yàn)閙ybatis會(huì)為mapper接口通過jdk動(dòng)態(tài)代理的方法生成接口的實(shí)現(xiàn)類,本篇文章將針對(duì)mapper接口的代理展開分析。 以下是mapper接口的代理模式的核心組件的類圖。

Mapper代理模式類圖

二、MapperRegistry

MapperRegistry通過Map結(jié)構(gòu)的屬性knownMappers中維護(hù)著mybatis中所有的mapper接口。

1. MapperRegistry#addMapper(class)

當(dāng)開發(fā)者在配置文件中配置了通過mappers節(jié)點(diǎn)的子節(jié)點(diǎn)mapper配置了mapper接口時(shí),會(huì)調(diào)用configuation#addMapper(Class)記錄mapper接口,而configuration又委托了MapperRegistry#addMapper(class)處理邏輯。

public <T> void addMapper(Class<T> type) {
  if (type.isInterface()) {
    if (hasMapper(type)) {
      throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
    }
    boolean loadCompleted = false;
    try {
      knownMappers.put(type, new MapperProxyFactory<T>(type));
      // It's important that the type is added before the parser is run
      // otherwise the binding may automatically be attempted by the
      // mapper parser. If the type is already known, it won't try.
      MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
      parser.parse();
      loadCompleted = true;
    } finally {
      if (!loadCompleted) {
        knownMappers.remove(type);
      }
    }
  }
}

可以看到,MapperRegistry以mapper接口的類型為key值,將接口類型封裝成MapperProxyFactory作為value值放入knownMappers。

2. MapperRegistry#getMapper(Class, SqlSession)

該方法基于SqlSession參數(shù)向外提供了對(duì)應(yīng)類型的mapper接口的對(duì)象。

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
  final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
  if (mapperProxyFactory == null) {
    throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
  }
  try {
    return mapperProxyFactory.newInstance(sqlSession);
  } catch (Exception e) {
    throw new BindingException("Error getting mapper instance. Cause: " + e, e);
  }
}

根據(jù)mapper接口類型找到對(duì)應(yīng)的MapperProxyFactory時(shí),調(diào)用其newInstance方法得到對(duì)應(yīng)的對(duì)象返回。

三、MapperProxyFactory

public class MapperProxyFactory<T> {
 
  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
 
  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }
 
  public Class<T> getMapperInterface() {
    return mapperInterface;
  }
 
  public Map<Method, MapperMethod> getMethodCache() {
    return methodCache;
  }
 
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
 
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }
}

如果對(duì)jdk動(dòng)態(tài)代理有一定了解,很容易就能看出來MapperProxyFactory的newInstance方法是很典型的生成代理對(duì)象的方式。

四、MapperProxy

MapperProxy作為InvocationHandler的實(shí)現(xiàn)類,是jdk動(dòng)態(tài)代理模式的核心。

1. MapperProxy#invoke(Object, Method, Object[])

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  try {
    if (Object.class.equals(method.getDeclaringClass())) {
      return method.invoke(this, args);
    } else if (isDefaultMethod(method)) {
      return invokeDefaultMethod(proxy, method, args);
    }
  } catch (Throwable t) {
    throw ExceptionUtil.unwrapThrowable(t);
  }
  final MapperMethod mapperMethod = cachedMapperMethod(method);
  return mapperMethod.execute(sqlSession, args);
}
 
private MapperMethod cachedMapperMethod(Method method) {
  MapperMethod mapperMethod = methodCache.get(method);
  if (mapperMethod == null) {
    mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
    methodCache.put(method, mapperMethod);
  }
  return mapperMethod;
}

對(duì)于Object方法和default方法,執(zhí)行原方法邏輯即可。 對(duì)于對(duì)于sql語句的方法,交給MapperMethod 處理。

五、MapperMethod

Mapper類負(fù)責(zé)去處理mapper接口中的sql方法。

public Object execute(SqlSession sqlSession, Object[] args) {
	 Object result;
	 switch (command.getType()) {
	   case INSERT: {
	 	Object param = method.convertArgsToSqlCommandParam(args);
	     result = rowCountResult(sqlSession.insert(command.getName(), param));
	     break;
	   }
	   case UPDATE: {
	     Object param = method.convertArgsToSqlCommandParam(args);
	     result = rowCountResult(sqlSession.update(command.getName(), param));
	     break;
	   }
	   case DELETE: {
	     Object param = method.convertArgsToSqlCommandParam(args);
	     result = rowCountResult(sqlSession.delete(command.getName(), param));
	     break;
	   }
	   case SELECT:
	     if (method.returnsVoid() && method.hasResultHandler()) {
	       executeWithResultHandler(sqlSession, args);
	       result = null;
	     } else if (method.returnsMany()) {
	       result = executeForMany(sqlSession, args);
	     } else if (method.returnsMap()) {
	       result = executeForMap(sqlSession, args);
	     } else if (method.returnsCursor()) {
	       result = executeForCursor(sqlSession, args);
	     } else {
	       Object param = method.convertArgsToSqlCommandParam(args);
	       result = sqlSession.selectOne(command.getName(), param);
	     }
	     break;
	   case FLUSH:
	     result = sqlSession.flushStatements();
	     break;
	   default:
	     throw new BindingException("Unknown execution method for: " + command.getName());
	 }
	 if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
	   throw new BindingException("Mapper method '" + command.getName() 
	       + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
	 }
	 return result;
}

MapperMethod還有一個(gè)靜態(tài)內(nèi)部類MethodSignature用作mapper方法的標(biāo)簽,SqlCommand用作sql命令。 可以看到,根據(jù)sql命令的類型(insert|update|delete|select|flush)和返回類型分別調(diào)用SqlSession的不同方法,然后對(duì)insert|update|delete方法的返回值做適配。

MapperMethod#rowCountResult(int)

private Object rowCountResult(int rowCount) {
 final Object result;
  if (method.returnsVoid()) {
    result = null;
  } else if (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType())) {
    result = rowCount;
  } else if (Long.class.equals(method.getReturnType()) || Long.TYPE.equals(method.getReturnType())) {
    result = (long)rowCount;
  } else if (Boolean.class.equals(method.getReturnType()) || Boolean.TYPE.equals(method.getReturnType())) {
    result = rowCount > 0;
  } else {
    throw new BindingException("Mapper method '" + command.getName() + "' has an unsupported return type: " + method.getReturnType());
  }
  return result;
}

insert|update|delete方法方法的返回值就是sql命令的匹配行數(shù),而在mapper方法中支持Integer、Long、Boolean和void類型的返回,因此做簡(jiǎn)單適配。

到此這篇關(guān)于Mybatis源碼解析之mapper接口的代理模式詳解的文章就介紹到這了,更多相關(guān)mapper接口的代理模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring Security整合KeyCloak保護(hù)Rest API實(shí)現(xiàn)詳解

    Spring Security整合KeyCloak保護(hù)Rest API實(shí)現(xiàn)詳解

    這篇文章主要為大家介紹了Spring Security整合KeyCloak保護(hù)Rest API實(shí)現(xiàn)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • Java List簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    Java List簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    Java中可變數(shù)組的原理就是不斷的創(chuàng)建新的數(shù)組,將原數(shù)組加到新的數(shù)組中,下文對(duì)Java List用法做了詳解。需要的朋友參考下吧
    2017-05-05
  • 詳談HashMap和ConcurrentHashMap的區(qū)別(HashMap的底層源碼)

    詳談HashMap和ConcurrentHashMap的區(qū)別(HashMap的底層源碼)

    下面小編就為大家?guī)硪黄斦凥ashMap和ConcurrentHashMap的區(qū)別(HashMap的底層源碼)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-08-08
  • 關(guān)于shiro中部分SpringCache失效問題的解決方法

    關(guān)于shiro中部分SpringCache失效問題的解決方法

    這篇文章主要給大家介紹了關(guān)于shiro中部分SpringCache失效問題的解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-07-07
  • Jenkins配置自動(dòng)發(fā)送郵件過程圖解

    Jenkins配置自動(dòng)發(fā)送郵件過程圖解

    這篇文章主要介紹了jenkins配置自動(dòng)發(fā)送郵件過程圖解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • java9區(qū)分opens與exports

    java9區(qū)分opens與exports

    本篇文章主要給大家講述了java9中opens與exports的區(qū)別以及用法的不同之處,一起學(xué)習(xí)下吧。
    2018-02-02
  • java實(shí)現(xiàn)基因序列比較的示例代碼

    java實(shí)現(xiàn)基因序列比較的示例代碼

    這篇文章主要介紹了java實(shí)現(xiàn)基因序列比較的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • springcloud項(xiàng)目占用內(nèi)存好幾個(gè)G導(dǎo)致服務(wù)器崩潰的問題

    springcloud項(xiàng)目占用內(nèi)存好幾個(gè)G導(dǎo)致服務(wù)器崩潰的問題

    這篇文章主要介紹了springcloud項(xiàng)目占用內(nèi)存好幾個(gè)G導(dǎo)致服務(wù)器崩潰的問題,本文給大家分享解決方案供大家參考,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-10-10
  • MyBatis參數(shù)處理實(shí)現(xiàn)方法匯總

    MyBatis參數(shù)處理實(shí)現(xiàn)方法匯總

    這篇文章主要介紹了MyBatis參數(shù)處理實(shí)現(xiàn)方法匯總,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • MyBatis控制臺(tái)顯示SQL語句的方法實(shí)現(xiàn)

    MyBatis控制臺(tái)顯示SQL語句的方法實(shí)現(xiàn)

    這篇文章主要介紹了MyBatis控制臺(tái)顯示SQL語句的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03

最新評(píng)論

堆龙德庆县| 安福县| 南安市| 龙胜| 中牟县| 塔城市| 齐齐哈尔市| 分宜县| 左云县| 扎赉特旗| 科尔| 敦煌市| 榆树市| 连云港市| 昭觉县| 金沙县| 道真| 兴安县| 台前县| 夏邑县| 廉江市| 宿迁市| 望谟县| 长兴县| 乐陵市| 康保县| 兴业县| 康保县| 奉化市| 通江县| 牡丹江市| 乌审旗| 本溪市| 吴川市| 察隅县| 南投市| 石家庄市| 孝义市| 姜堰市| 邵东县| 万盛区|