(二)MyBatis調用動態代理解析----MyBatis源碼解析

如果我們要使用MyBatis進行數據庫操作的話,大致要做兩件事情: 
1. 定義DAO接口 
在DAO接口中定義需要進行的數據庫操作。 
2. 創建映射文件 
當有了DAO接口後,還需要爲該接口創建映射文件。映射文件中定義了一系列SQL語句,這些SQL語句和DAO接口一一對應。

MyBatis在初始化的時候會將映射文件與DAO接口一一對應,並根據映射文件的內容爲每個函數創建相應的數據庫操作能力。而我們作爲MyBatis使用者,只需將DAO接口注入給Service層使用即可。 
那麼MyBatis是如何根據映射文件爲每個DAO接口創建具體實現的?答案是——動態代理。 

首先來回顧一項MyBatis在初始化過程中所做的事情。 
MyBatis在初始化過程中,首先會讀取我們的配置文件流程,並使用XMLConfigBuilder來解析配置文件。XMLConfigBuilder會依次解析配置文件中的各個子節點,如:<settings><typeAliases><mappers>等。這些子節點在解析完成後都會被註冊進configuration對象。然後configuration對象將作爲參數,創建SqlSessionFactory對象。至此,初始化過程完畢! 
下面我們重點分析<mapper>節點解析的過程。

節點解析過程

XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration,
 resource, configuration.getSqlFragments());
mapperParser.parse();

由上述代碼可知,解析mapper節點的解析是由XMLMapperBuilder類的parse()函數來完成的,下面我們就詳細看一下parse()函數。

public void parse() {
    // 若當前Mapper.xml尚未加載,則加載
    if (!configuration.isResourceLoaded(resource)) {
      // 解析<mapper>節點
      configurationElement(parser.evalNode("/mapper"));
      // 將當前Mapper.xml標註爲『已加載』(下回就不用再加載了)
      configuration.addLoadedResource(resource);
      // 【關鍵】將Mapper Class添加至Configuration中
      bindMapperForNamespace();
    }
 
    parsePendingResultMaps();
    parsePendingCacheRefs();
    parsePendingStatements();
}

這個函數主要做了兩件事: 
1. 解析<mapper>節點,並將解析結果註冊進configuration中; 
2. 將當前映射文件所對應的DAO接口的Class對象註冊進configuration中 
這一步極爲關鍵!是爲了給DAO接口創建代理對象,下文會詳細介紹。

下面再進入bindMapperForNamespace()函數,看一看它做了什麼:

private void bindMapperForNamespace() {
    // 獲取當前映射文件對應的DAO接口的全限定名
    String namespace = builderAssistant.getCurrentNamespace();
    if (namespace != null) {
      // 將全限定名解析成Class對象
      Class<?> boundType = null;
      try {
        boundType = Resources.classForName(namespace);
      } catch (ClassNotFoundException e) {

      }
      if (boundType != null) {
        if (!configuration.hasMapper(boundType)) {
          // 將當前Mapper.xml標註爲『已加載』(下回就不用再加載了)
          configuration.addLoadedResource("namespace:" + namespace);
          // 將DAO接口的Class對象註冊進configuration中
          configuration.addMapper(boundType);
        }
      }
    }
}

這個函數主要做了兩件事: 
1. 將<mapper>節點上定義的namespace屬性(即:當前映射文件所對應的DAO接口的權限定名)解析成Class對象 
2. 將該Class對象存儲在configuration對象的MapperRegistry容器中。

可以看一下MapperRegistry

public class MapperRegistry {
  private final Configuration config;
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
}

MapperRegistry有且僅有兩個屬性:ConfigurationknownMappers。 
其中,knownMappers的類型爲Map<Class<?>, MapperProxyFactory<?>>,由此可見,它是一個Map,key爲DAO接口的Class對象,而Value爲該DAO接口代理對象的工廠。 
那麼,這個代理對象工廠是何許人也?它又是如何產生的呢?我們先來看一下MapperRegistryaddMapper()函數。

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 {
      // 創建MapperProxyFactory對象,並put進knownMappers中
      knownMappers.put(type, new MapperProxyFactory<T>(type));
      MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
      parser.parse();
      loadCompleted = true;
    }
    finally {
      if (!loadCompleted) {
        knownMappers.remove(type);
      }
    }
  }
}

從這個函數可知,MapperProxyFactory是在這裏創建,並put進knownMappers中的。 
下面我們就來看一下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);
  }
}

這個類有三個重要成員: 
1. mapperInterface屬性 
這個屬性就是DAO接口的Class對象,當創建MapperProxyFactory對象的時候需要傳入 
2. methodCache屬性 
這個屬性用於存儲當前DAO接口中所有的方法。 
3. newInstance函數 
這個函數用於創建DAO接口的代理對象,它需要傳入一個MapperProxy對象作爲參數。而MapperProxy類實現了InvocationHandler接口,由此可知它是動態代理中的處理類,所有對目標函數的調用請求都會先被這個處理類截獲,所以可以在這個處理類中添加目標函數調用前、調用後的邏輯。

-----------------------------------------------華麗的分割線--------------------------------------------------------

DAO函數調用過程

當MyBatis初始化完畢後,configuration對象中存儲了所有DAO接口的Class對象和相應的MapperProxyFactory對象(用於創建DAO接口的代理對象)。接下來,就到了使用DAO接口中函數的階段了。

SqlSession sqlSession = sqlSessionFactory.openSession();
try {
    ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
    List<Product> productList = productMapper.selectProductList();
    for (Product product : productList) {
        System.out.printf(product.toString());
    }
} finally {
    sqlSession.close();
}

我們首先需要從sqlSessionFactory對象中創建一個SqlSession對象,然後調用sqlSession.getMapper(ProductMapper.class)來獲取代理對象。 
我們先來看一下sqlSession.getMapper()是如何創建代理對象的?

public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
}

sqlSession.getMapper()調用了configuration.getMapper(),那我們再看一下configuration.getMapper()

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
}

configuration.getMapper()又調用了mapperRegistry.getMapper(),那好,我們再深入看一下mapperRegistry.getMapper()

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

看到這裏我們就恍然大悟了,原來它根據上游傳遞進來DAO接口的Class對象,從configuration中取出了該DAO接口對應的代理對象生成工廠:MapperProxyFactory; 
在有了這個工廠後,再通過newInstance函數創建該DAO接口的代理對象,並返回給上游。

OK,此時我們已經獲取了代理對象,接下來就可以使用這個代理對象調用相應的函數了。

SqlSession sqlSession = sqlSessionFactory.openSession();
try {
    ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
    List<Product> productList = productMapper.selectProductList();
    for (Product product : productList) {
        System.out.printf(product.toString());
    }
} finally {
    sqlSession.close();
}

以上述代碼爲例,當我們獲取到ProductMapper的代理對象後,我們調用了它的selectProductList()函數。 
下面我們就來分析下代理函數調用過程。

當調用了代理對象的某一個代理函數後,這個調用請求首先會被髮送給代理對象處理類MapperProxyinvoke()函數:

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

先來解釋下invoke函數的幾個參數: 
1. Object proxy:代理對象 
2. Method method:當前正在被調用的代理對象的函數對象 
3. Object[] args:調用函數的所有入參

然後,直接看invoke函數最核心的兩行代碼: 
1. cachedMapperMethod(method):從當前代理對象處理類MapperProxymethodCache屬性中獲取method方法的詳細信息(即:MapperMethod對象)。如果methodCache中沒有就創建並加進去。 
2. 有了MapperMethod對象後執行它的execute()方法,該方法就會調用JDBC執行相應的SQL語句,並將結果返回給上游調用者。至此,代理對象函數的調用過程結束! 
那麼execute()函數究竟做了什麼?它是如何執行SQL語句的? 
預知後事如何,且聽下回分解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章