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>節點解析的過程。

<mapper>節點解析過程

ProductMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="team.njupt.mapper.ProductMapper">
    <select id="selectProductList" resultType="com.jp.entity.Product">
        select * from product
    </select>
</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<?>>,由此可見,它是一個 Mapkey為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函數最核心的兩行代碼:

  • cachedMapperMethod(method):從當前代理對象處理類MapperProxymethodCache屬性中獲取method方法的詳細信息(即:MapperMethod對象)。如果methodCache中沒有就創建並加進去。
  • 有了MapperMethod對象后執行它的execute()方法,該方法就會調用JDBC執行相應的SQL語句,並將結果返回給上游調用者。至此,代理對象函數的調用過程結束!
    那么execute()函數究竟做了什么?它是如何執行SQL語句的?

 

轉自:https://www.jianshu.com/p/46c6e56d9774


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM