1. 程式人生 > >MyBatis中Mapper的產生原始碼分析

MyBatis中Mapper的產生原始碼分析

呼叫getMapper方法

SqlSession#getMapper->(DefaultSqlSession)configuration#getMapper–>(Configuration)mapperRegistry#getMapper

//MapperRegistry類
@SuppressWarnings("unchecked")
  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);
    }
  }
//MapperProxyFactroy類
@SuppressWarnings("unchecked")
//這裡即產生一個mapper介面的代理物件 代理物件的呼叫在下面類中體現
  protected T newInstance(MapperProxy<T> mapperProxy) {
      //引數分別為Mapper介面的類載入器、mapper介面、對應的invocationHandler
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
//MapperRegistry呼叫的是這個方法 這個方法又呼叫上面產生代理物件的方法
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }
//MapperProxy類
@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        //如果該方法是Object中的基本方法 則呼叫這個迴圈程式碼
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
          //如果介面方法是被Default修飾符修飾 則呼叫這個迴圈程式碼
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
      //否則該方法即是Mapper中宣告的方法 即呼叫SqlSession來執行
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

綜上可以看出Mapper是基於動態代理產生出來的。