mybatis源码探索之代理封装阶段

版本

mybatis版本3.5.7

背景

我们在使用mybatis进行数据库crud时通常都是通过*Mapper.java对象的方法进行操作的,那sql语句怎么和对应的方法绑定的,mybatis是怎么知道返回结果是多个、单个或者是其他的,*Mapper是个接口,它是怎么实例化调用方法的。这些一系列问题背后怎么实现的,都是跟binding模块相关的。

实现步骤

要实现以上操作有三个步骤:
1、根据sql语句类型和参数选择调用不同的方法
2、通过找到命名空间和方法名
3、传递参数
完成以上三个主要步骤就绑定成功了,要完成以上步骤需要下面几个核心类。

核心类

MapperRegistry

MapperRegistry 是mapper 接口和对应的代理对象工厂的注册中心。MapperRegistry 内部维护着一个Map对象,key是mapper接口的Class对象,value是MapperProxyFactory。

当需要获取mapper接口对象时就需要调用SqlSession#getMapper方法,getMapper是从configuration对象的MapperRegistry获取一个代理对象工厂。

SqlSession#getMapper:

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

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

在配置加载阶段会往Configuration对象的属性mapperRegistry中添加mapper接口和代理工厂映射,
添加入口是Configuration#addMappers和Configuration#addMapper,前者是把某个包下的mapper接口添加进去,后者只是添加单独一个mapper接口,最终都是调用MapperRegistry#addMapper。
MapperRegistry#addMapper

/**
   * 把mapper 接口添加到 knownMappers 中注册中心
   * @param type
   * @param <T>
   */
  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 {
        // 建立mapper 和 MapperProxyFactory 的连接
        knownMappers.put(type, new MapperProxyFactory<>(type));
        // It's important that the type is added before the parser is run
        // otherwise the binding may automatically be attempted by the
        // mapper parser. If the type is already known, it won't try.

        // 解析接口上的注解信息并添加到configuration对象中
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();

        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }

MapperProxyFactory

MapperProxyFactory是MapperProxy的工厂类,专门用来生产MapperProxy的。
MapperProxyFactory:

public class MapperProxyFactory<T> {

  /**
   * mapper接口的Class对象
   */
  private final Class<T> mapperInterface;
  /**
   * key: mapper接口的一个方法的Method对象
   * value: 对应的MapperMethodInvoker对象
   */
  private final Map<Method, MapperMethodInvoker> methodCache = new ConcurrentHashMap<>();

  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }

  public Class<T> getMapperInterface() {
    return mapperInterface;
  }

  public Map<Method, MapperMethodInvoker> getMethodCache() {
    return methodCache;
  }

  /**
   * 创建mapperInterface接口的实现类的代理对象
   * @param mapperProxy
   * @return
   */
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    T proxyInstance = (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
    return proxyInstance;
  }

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

mapper接口的代理类形如org.apache.ibatis.binding.MapperProxy@3d5c822d
在这里插入图片描述

MapperProxy

MapperProxy是在MapperProxyFactory#newInstance(SqlSession sqlSession)方法中生成实例对象的。
MapperProxy实现了InvocationHandler,使用的jdk的动态代理,对mapper接口进行了增强。
既然MapperProxy实现了InvocationHandler接口,那就从invoke开始看起。

@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 {
        return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }

接下来看cachedInvoker方法:

/**
   * 缓存method对应的MapperMethodInvoker对象
   * @param method
   * @return
   * @throws Throwable
   */
  private MapperMethodInvoker cachedInvoker(Method method) throws Throwable {
    try {
      // A workaround for https://bugs.openjdk.java.net/browse/JDK-8161372
      // It should be removed once the fix is backported to Java 8 or
      // MyBatis drops Java 8 support. See gh-1929
      MapperMethodInvoker invoker = methodCache.get(method);
      if (invoker != null) {
        return invoker;
      }

      return methodCache.computeIfAbsent(method, m -> {
        //如果是接口的default方法生成DefaultMethodInvoker
        if (m.isDefault()) {
          try {
            if (privateLookupInMethod == null) {
              return new DefaultMethodInvoker(getMethodHandleJava8(method));
            } else {
              return new DefaultMethodInvoker(getMethodHandleJava9(method));
            }
          } catch (IllegalAccessException | InstantiationException | InvocationTargetException
              | NoSuchMethodException e) {
            throw new RuntimeException(e);
          }
        } else {
          //生成非default方法MethodInvoker
          return new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
        }
      });
    } catch (RuntimeException re) {
      Throwable cause = re.getCause();
      throw cause == null ? re : cause;
    }
  }

MapperMethodInvoker

MapperMethodInvoker是MapperProxy的内部类。
MapperMethodInvoker对于接口中非default方法来说它是MapperMethod的调用者,它的实现PlainMethodInvoker里面维护着一个MapperMethod,真正的执行者还是MapperMethod。
DefaultMethodInvoker内部就直接调用了default方法。重点还是要看PlainMethodInvoker
PlainMethodInvoker

/**
   * 接口中非default方法的调用器
   */
  private static class PlainMethodInvoker implements MapperMethodInvoker {
    private final MapperMethod mapperMethod;

    public PlainMethodInvoker(MapperMethod mapperMethod) {
      super();
      this.mapperMethod = mapperMethod;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
      //调用mapperMethod对象执行sql
      return mapperMethod.execute(sqlSession, args);
    }
  }

PlainMethodInvoker的invoke方法内部也没有对参数做什么别的逻辑操作而是直接转发给MapperMethod#execute方法,让MapperMethod来执行,MapperMethod也是最后真正的执行者。

MapperMethod

MapperMethod才是binding模块真正的执行者,上述的三个步骤也都是在MapperMethod中实现的。
三个步骤:
1、根据sql语句类型和参数选择调用不同的方法
2、找到命名空间和方法名
3、传递参数

属性

MapperMethod内部有两个属性,SqlCommand和MethodSignature对象,它们也都是MapperMethod的内部类。

//mapper接口中方法的命名空间和sql类型
  private final SqlCommand command;
  //mapper接口中的方法签名,包括参数、返回类型等信息
  private final MethodSignature method;

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

SqlCommand

SqlCommand的作用是获取sql命名空间和sql语句的类型。
SqlCommand源码,删除了一些getter方法。

public static class SqlCommand {
    //sql的命名空间
    private final String name;
    //sql语句类型,UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH
    private final SqlCommandType type;

    public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
      final String methodName = method.getName();
      final Class<?> declaringClass = method.getDeclaringClass();
      //从configuration对象获取MappedStatement对象
      MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
          configuration);
      if (ms == null) {
        //判断没有Flush注解
        if (method.getAnnotation(Flush.class) != null) {
          name = null;
          type = SqlCommandType.FLUSH;
        } else {
          throw new BindingException("Invalid bound statement (not found): "
              + mapperInterface.getName() + "." + methodName);
        }
      } else {
        name = ms.getId();
        type = ms.getSqlCommandType();
        if (type == SqlCommandType.UNKNOWN) {
          throw new BindingException("Unknown execution method for: " + name);
        }
      }
    }

    //从configuration对象获取MappedStatement对象
    private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,
        Class<?> declaringClass, Configuration configuration) {
        //接口全限定名假方法名组成statementId,如 mapperClasses.UserInfoMapper.selectByPrimaryKey
      String statementId = mapperInterface.getName() + "." + methodName;
      if (configuration.hasStatement(statementId)) {
        return configuration.getMappedStatement(statementId);
      } else if (mapperInterface.equals(declaringClass)) {
        //如果是方法的所在的接口
        return null;
      }
      for (Class<?> superInterface : mapperInterface.getInterfaces()) {
        //递归查找直到找到对应MappedStatement对象
        if (declaringClass.isAssignableFrom(superInterface)) {
          MappedStatement ms = resolveMappedStatement(superInterface, methodName,
              declaringClass, configuration);
          if (ms != null) {
            return ms;
          }
        }
      }
      return null;
    }
  }

MethodSignature

MethodSignature 作用是解析方法的参数、返回值类型等信息。
MethodSignature源码,删除了一些getter方法。

 public static class MethodSignature {
    //返回结果是集合或者数组
    private final boolean returnsMany;
    //返回结果是map对象
    private final boolean returnsMap;
    private final boolean returnsVoid;
    private final boolean returnsCursor;
    private final boolean returnsOptional;
    //返回类型
    private final Class<?> returnType;
    //@MapKey注解的value,也就是属性名或者列名
    private final String mapKey;
    private final Integer resultHandlerIndex;
    private final Integer rowBoundsIndex;
    //方法的参数解析器,将参数转为map
    private final ParamNameResolver paramNameResolver;

    public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
      //获取方法返回值类型
      Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);
      if (resolvedReturnType instanceof Class<?>) {
        this.returnType = (Class<?>) resolvedReturnType;
      } else if (resolvedReturnType instanceof ParameterizedType) {
        this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();
      } else {
        this.returnType = method.getReturnType();
      }
      this.returnsVoid = void.class.equals(this.returnType);
      this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray();
      this.returnsCursor = Cursor.class.equals(this.returnType);
      this.returnsOptional = Optional.class.equals(this.returnType);
      this.mapKey = getMapKey(method);
      this.returnsMap = this.mapKey != null;
      this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
      this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);
      this.paramNameResolver = new ParamNameResolver(configuration, method);
    }

    public Object convertArgsToSqlCommandParam(Object[] args) {
      return paramNameResolver.getNamedParams(args);
    }

    public boolean hasRowBounds() {
      return rowBoundsIndex != null;
    }

    public RowBounds extractRowBounds(Object[] args) {
      return hasRowBounds() ? (RowBounds) args[rowBoundsIndex] : null;
    }

    public boolean hasResultHandler() {
      return resultHandlerIndex != null;
    }

    public ResultHandler extractResultHandler(Object[] args) {
      return hasResultHandler() ? (ResultHandler) args[resultHandlerIndex] : null;
    }
  
    /**
     * return whether return type is {@code java.util.Optional}.
     *
     * @return return {@code true}, if return type is {@code java.util.Optional}
     * @since 3.5.0
     */
    public boolean returnsOptional() {
      return returnsOptional;
    }

    /**
     * 获取参数唯一下标
     * @param method
     * @param paramType
     * @return
     */
    private Integer getUniqueParamIndex(Method method, Class<?> paramType) {
      Integer index = null;
      final Class<?>[] argTypes = method.getParameterTypes();
      for (int i = 0; i < argTypes.length; i++) {
        //判断paramType是否是参数的父类或者superinterface ,true返回下标
        if (paramType.isAssignableFrom(argTypes[i])) {
          if (index == null) {
            index = i;
          } else {
            throw new BindingException(method.getName() + " cannot have multiple " + paramType.getSimpleName() + " parameters");
          }
        }
      }
      return index;
    }

    /**
     * 获取MapKey注解value
     * @param method
     * @return
     */
    private String getMapKey(Method method) {
      String mapKey = null;
      if (Map.class.isAssignableFrom(method.getReturnType())) {
        final MapKey mapKeyAnnotation = method.getAnnotation(MapKey.class);
        if (mapKeyAnnotation != null) {
          mapKey = mapKeyAnnotation.value();
        }
      }
      return mapKey;
    }
  }

方法

MapperMethod核心方法是MapperMethod#execute方法

execute

execute方法中的executeFor*方法最终都会根据返回值是集合、void、map等调用sqlSession对象中相应的方法。

public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    //步骤一:根据sql语句类型和参数选择调用不同的方法
    switch (command.getType()) {
      case INSERT: {
        //步骤三:将参数转为map
        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()) { //返回类型是void
          executeWithResultHandler(sqlSession, args);
          result = null;
        } else if (method.returnsMany()) { //返回类型是集合或者数组
          result = executeForMany(sqlSession, args);
        } else if (method.returnsMap()) {
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
          result = executeForCursor(sqlSession, args);
        } else {
          Object param = method.convertArgsToSqlCommandParam(args);
          result = sqlSession.selectOne(command.getName(), param);
          if (method.returnsOptional()
              && (result == null || !method.getReturnType().equals(result.getClass()))) {
            result = Optional.ofNullable(result);
          }
        }
        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;
  }

convertArgsToSqlCommandParam

convertArgsToSqlCommandParam是代理封装阶段的最后一个步骤,把参数转为map然后进行传递。它是MethodSignature的对象方法,最终调用的是ParamNameResolver#getNamedParams方法,

/**
   * <p>
   * A single non-special parameter is returned without a name.
   * Multiple parameters are named using the naming rule.
   * In addition to the default names, this method also adds the generic names (param1, param2,
   * ...).
   * </p>
   *
   * @param args
   *          the args
   * @return the named params
   */
  public Object getNamedParams(Object[] args) {
    final int paramCount = names.size();
    if (args == null || paramCount == 0) {
      return null;
    } else if (!hasParamAnnotation && paramCount == 1) {
      //没有@Param注解并且是单个参数,直接返回参数值
      Object value = args[names.firstKey()];
      return wrapToMapIfCollection(value, useActualParamName ? names.get(0) : null);
    } else {
      final Map<String, Object> param = new ParamMap<>();
      int i = 0;
      for (Map.Entry<Integer, String> entry : names.entrySet()) {
        param.put(entry.getValue(), args[entry.getKey()]);
        // 生成key是GENERIC_NAME_PREFIX前缀的参数 (param1, param2, ...),value是参数的entry.getValue()
        final String genericParamName = GENERIC_NAME_PREFIX + (i + 1);
        // 确保不覆盖以@Param命名的参数
        if (!names.containsValue(genericParamName)) {
          param.put(genericParamName, args[entry.getKey()]);
        }
        i++;
      }
      return param;
    }
  }

总结

代理封装阶段三个步骤对应的方法
1、根据sql语句类型和参数选择调用不同的方法
MapperMethod#execute中根据sql语句类型和参数选择调用不同的方法
2、找到命名空间和方法名
SqlCommand#resolveMappedStatement中根据方法名和接口获取MappedStatement对象,从而获取到命名空间
3、传递参数
MethodSignature#convertArgsToSqlCommandParam方法调用ParamNameResolver#getNamedParams将参数转为map进行传递

能力一般,水平有限,如有错误,请多指出。

posted @ 2022-04-29 19:05  码猿笔记  阅读(28)  评论(0编辑  收藏  举报