MyBatis 源码阅读笔记:Mapper 方法调用过程

in TCEHJava with 0 comment

前言

沿用上一篇《MyBatis 源码阅读笔记:Mapper 接口的注册过程》的示例,继续阅读 Mapper 方法调用都做了哪些事情?
方法调用前先要实例化,因此就此前的例子,接下来阅读 SqlSession#getMapper 方法里都做了哪些操作。

getMapper() 方法

DefaultSqlSession#getMapper

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

getMapper() 方法

Configuration#getMapper

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

getMapper() 方法

MapperRegistry#getMapper

  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // 上一篇笔记中聊过,符合条件的 Mapper ,会缓存到 knownMappers 中
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    // 从缓存中获取不到 Mapper
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      // 能获取到 Mapper ,开始实例化
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

newInstance() 方法

MapperProxyFactory#newInstance

  public T newInstance(SqlSession sqlSession) {
    // 构建 MapperProxy 代理对象
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

newInstance() 方法

 protected T newInstance(MapperProxy<T> mapperProxy) {
    // 使用 JDK 动态代理技术为 Mapper 生成代理对象
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

MapperProxy 类

调用 Mapper 方法,其实就是动态代理回调到 invoke() 方法

public class MapperProxy<T> implements InvocationHandler, Serializable {

  private static final long serialVersionUID = -6424540398559729838L;
  private final SqlSession sqlSession;
  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache;

  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
    // 缓存数据
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }

  @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)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    // 尝试从缓存中获取封装的 MapperMethod 对象,没有则封装成 MapperMethod ,并缓存到 methodCache 中
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    // 执行 MapperMethod 方法
    return mapperMethod.execute(sqlSession, args);
  }

  private MapperMethod cachedMapperMethod(Method method) {
    // 从缓存获取 MapperMethod 
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      // 没获取到,封装新的 MapperMethod 
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      // 添加到缓存中
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }

  @UsesJava7
  private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
      throws Throwable {
    final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
        .getDeclaredConstructor(Class.class, int.class);
    if (!constructor.isAccessible()) {
      constructor.setAccessible(true);
    }
    final Class<?> declaringClass = method.getDeclaringClass();
    return constructor
        .newInstance(declaringClass,
            MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
                | MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
        .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
  }

  /**
   * Backport of java.lang.reflect.Method#isDefault()
   */
  private boolean isDefaultMethod(Method method) {
    return (method.getModifiers()
        & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC
        && method.getDeclaringClass().isInterface();
  }
}

MapperMethod() 构造方法

MapperMethod#MapperMethod

  public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new SqlCommand(config, mapperInterface, method);
    this.method = new MethodSignature(config, mapperInterface, method);
  }

execute() 方法

MapperMethod#execute

  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    switch (command.getType()) {
      case INSERT: {
        // 添加参数到到SQL
        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()) {
          // 返回类型为 Map 且带 @MapKey 注解
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
          // 返回类型为 Cursor
          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;
  }

总结