MyBatis(3)getMapper()的实现

1.SqlSession.getMapper()

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

2.Configuration.getMapper()

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

3.MapperRegistry.getMapper()

public  T getMapper(Class type, SqlSession sqlSession) {
    //这是一个HashMap,取出注册的Mapper工厂
    final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) knownMappers.get(type);
    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);
    }
}

4.MapperProxyFactory.newInstance

public T newInstance(SqlSession sqlSession) {
    //生成Mapper代理类
    final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
}

protected T newInstance(MapperProxy mapperProxy) {
    //根据代理类,生成代理对象,实现Mapper接口
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

5.MapperProxy.构造器

public class MapperProxy implements InvocationHandler, Serializable

public MapperProxy(SqlSession sqlSession, Class mapperInterface, Map methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //判断是不是toString(),hashCode()这种默认方法
      //这样的方法不需要处理
      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);
    //对SqlSession的包装调用
    return mapperMethod.execute(sqlSession, args);
  }

5.MapperMethod代理机制的核心类

public class MapperMethod {
  //封装了SQL标签,包括CRUD
  private final SqlCommand command;
  //封装了方法的参数信息和返回类型信息等
  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);
  }

  //对SqlSession的包装调用
  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    switch (command.getType()) {
      //如果是INSERT操作
      case INSERT: {
        //处理参数,将参数加进SQL的语句里面
        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()) {
          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;
  }

private  Object executeForMany(SqlSession sqlSession, Object[] args) {
    List result;
    Object param = method.convertArgsToSqlCommandParam(args);
    if (method.hasRowBounds()) {
      RowBounds rowBounds = method.extractRowBounds(args);
      result = sqlSession.selectList(command.getName(), param, rowBounds);
    } else {
      result = sqlSession.selectList(command.getName(), param);
    }
    // issue #510 Collections & arrays support
    if (!method.getReturnType().isAssignableFrom(result.getClass())) {
      if (method.getReturnType().isArray()) {
        return convertToArray(result);
      } else {
        return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
      }
    }
    return result;
}

........

}

看到这里,我们会发现SqlSession.getMapper()就是绕一大圈去动态代理一个对象。这个对象根据返回类型和参数类型,最后用SqlSession的方法。

MapperMethod里面封装了自动根据配置,来使用SqlSession里面的方法。

6.SqlCommand和MethodSignature

  public static class SqlCommand {
    //XML标签的ID
    private final String name;
    //CRUD的标签