MyBatis(3)getMapper()的实现

来源:互联网 发布:学佛软件下载 编辑:程序博客网 时间:2024/06/06 05:36

1.SqlSession.getMapper()

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

2.Configuration.getMapper()

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

3.MapperRegistry.getMapper()

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {    //这是一个HashMap,取出注册的Mapper工厂    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) 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<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);    return newInstance(mapperProxy);}protected T newInstance(MapperProxy<T> 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<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 {      //判断是不是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 <E> Object executeForMany(SqlSession sqlSession, Object[] args) {    List<E> result;    Object param = method.convertArgsToSqlCommandParam(args);    if (method.hasRowBounds()) {      RowBounds rowBounds = method.extractRowBounds(args);      result = sqlSession.<E>selectList(command.getName(), param, rowBounds);    } else {      result = sqlSession.<E>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的标签<select><update>...    private final SqlCommandType type;    public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {      final String methodName = method.getName();      final Class<?> declaringClass = method.getDeclaringClass();      //MappedStatement封装了一个配置文件(xml)的所有信息      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 {        name = ms.getId();        type = ms.getSqlCommandType();        if (type == SqlCommandType.UNKNOWN) {          throw new BindingException("Unknown execution method for: " + name);        }      }    }    public String getName() {      return name;    }    public SqlCommandType getType() {      return type;    }    private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,        Class<?> declaringClass, Configuration configuration) {      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()) {        if (declaringClass.isAssignableFrom(superInterface)) {          MappedStatement ms = resolveMappedStatement(superInterface, methodName,              declaringClass, configuration);          if (ms != null) {            return ms;          }        }      }      return null;    }  }
  public static class MethodSignature {    //是否返回多调结果    private final boolean returnsMany;    //返回Map    private final boolean returnsMap;    private final boolean returnsVoid;    private final boolean returnsCursor;    //自定义的返回类型    private final Class<?> returnType;    private final String mapKey;    private final Integer resultHandlerIndex;    private final Integer rowBoundsIndex;    private final ParamNameResolver paramNameResolver;

看完上面的分析,就是通过一些方法的信息生成一个Mapper代理对象,并调用SqlSession的方法查询结果。

下次看看SqlSession的实现吧。

原创粉丝点击