Mybatis学习系列(七):Mapper执行

第六篇文章我们拿到了Mapper的一个代理对象,我们知道代理对象的执行其实是交给了InvocationHandler来处理的,也就是我们的MapperProxy对象。我们看一下invoke方法:

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);
    }
    //我们根据当前的方法在缓存中获取MapperMethod 
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //执行相应的方法
    return mapperMethod.execute(sqlSession, args);
  }

1.获取MapperMethod 

private MapperMethod cachedMapperMethod(Method method) {
    //在缓存中获取
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      //如果没有生成mapperMethod 
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      //加入当前缓存
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }

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

1.1初始化SqlCommand对象

public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
      //获取当前方法名称
      final String methodName = method.getName();
      //获取当前方法 所属的类
      final Class<?> declaringClass = method.getDeclaringClass();
      //这里获取MappedStatement 也就是我们解析mapper时生成的
      MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
          configuration);
      if (ms == null) {
        if (method.getAnnotation(Flush.class) != null) {
          name = null;
          type = SqlCommandType.FLUSH;
        } else {
          throw new BindingException("Invalid bound statement (not found): "
              + mapperInterface.getName() + "." + methodName);
        }
      } else {
        //这里获取MappedStatement 的ID
        name = ms.getId();
        //当前SQL的类型(增删改查)
        type = ms.getSqlCommandType();
        if (type == SqlCommandType.UNKNOWN) {
          throw new BindingException("Unknown execution method for: " + name);
        }
      }
    }

1.1.1获取MappedStatement 

private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,
        Class<?> declaringClass, Configuration configuration) {
      //组装ID 其实就是 之前设定的namespace.定义的ID(方法名称)
      String statementId = mapperInterface.getName() + "." + methodName;
      //根据ID在缓存中获取到了 直接返回
      if (configuration.hasStatement(statementId)) {
        return configuration.getMappedStatement(statementId);
      } else if (mapperInterface.equals(declaringClass)) {
        return null;
      }
      //如果当前方法不在当前接口中  往父类接口找
      for (Class<?> superInterface : mapperInterface.getInterfaces()) {
        if (declaringClass.isAssignableFrom(superInterface)) {
          MappedStatement ms = resolveMappedStatement(superInterface, methodName,
              declaringClass, configuration);
          if (ms != null) {
            return ms;
          }
        }
      }
      return null;
    }
  }

1.2初始化MethodSignature对象

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();
      }
      //是不是没有返回值  void类型
      this.returnsVoid = void.class.equals(this.returnType);
      //返回的类型  是不是集合或者数组
      this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray();
      this.returnsCursor = Cursor.class.equals(this.returnType);
      //返回的map类型
      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);
    }

2.执行相应的方法

public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    //判断当前sql的类型(增删改查)
    switch (command.getType()) {
      case INSERT: {
      //解析入参
      Object param = method.convertArgsToSqlCommandParam(args);
        //调用sqlSession的insert方法
        //返回执行的行数
        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
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
          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;
  }

这里可以最终调用的是sqlsession的方法,下一篇我们将详细介绍每一个方法。

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