日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Mybatis3 深入源碼 -- getMapper返回代理mapper源碼分析

作者:Survivor001 更新時間: 2022-02-15 編程語言

經過前兩篇文章的分析,我們知道了mybatis對配置文件mybatis-config.xml和mapper.xml 的一個加載原理,以及配置信息Configuraction和執行器Excutor 信息封裝入DefaultSqlSession中。

現在針對mapper相關源碼進行解析,分析Mybaits是如果沒有實體類的情況下,可以執行接口方法?

示例:

?進入getmapper方法,實現類DefaultSqlSession:

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

?繼續:

 public T newInstance(SqlSession sqlSession) {
  
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

MapperProxy類,該類實現了InvocationHandler接口,實現了invoke方法。

?回過頭進入newInstance方法:

  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

這就很清楚了創建了一個jdk代理對象。

?

總結 : getmapper方法創建了mapper接口的JDK代理對接,并返回。因為mapper接口核心目的是提供sql方法的全限定名,使用其找到對應的存儲在mappedstatements中的xml配置sql內容,執行sql,所以這就是為什么不需要實現類就可以進行方法調用的根本原因:通過代理實現調用invoke方法實現mappedstatement配置的匹配。

原文鏈接:https://blog.csdn.net/qq_31142237/article/details/120410946

欄目分類
最近更新