1、sqlSesseion.getMapper(UserMapper.class)获取UserMapper的代理对象。通过Debug方式发现这里使用SqlSesseion的实现类DefaultSqlSession。

2、找到DeaultSqlSession中的getMapper方法,发现这里没有做其他的操作,只是将工作继续抛到了Configuration类中,直接进入该类的getMapper方法中。找到Configuration类的getMapper方法,这里也是将工作继续交到MapperRegistry的getMapper的方法。找到MapperRegistry的getMapper的到方法,看到是通过MapperProxyFactory的newInstance方法创建MapperProxy的代理类。(MapperRegistry用于注册、获取和判断Mapper接口是否已经被注册。)

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // knownMappers集合中实现Mapper类到Mapper代理工厂的映射,在将Mapper类添加至集合后还必须完成一次xml配置解析,如果解析不成功会将mapper接口移除,感兴趣可自行了解MapperAnnotationBuilder是如何进行解析的。
    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);
    }
  }

3、找到MapperProxyFactory的newIntance方法,通过方法的调用参数类型可以得知,是调用第二个newInstance方法创建MapperProxy对象,第二个方法再调用第一个newInstance方法并将MapperProxy对象传入进去,根据该对象创建代理类并返回。这里已经得到需要的代理类了,但是我们的代理类所做的工作还得继续向下查看MapperProxy类。

 protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

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

4、找到MapperProxy类,发现其实现了JDK动态代理必须实现的接口InvocationHandler,这里看到在invoke方法里先获取MapperMethod类,然后调用mapperMethod.execute(),所以我们继续查看MapperMethod类的execute方法。 

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
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    // 代理接口抽象方法
    return mapperMethod.execute(sqlSession, args);
  }

5、找到MapperMethod类的execute方法,execute方法实质是对SqlSession中的操作进行了封装使用。MapperProxy应该算作一个包装类,本身不做任何事情,最主要的作用是维系着<Mapper.Method,MapperMethod>集合。这样mapper接口就知道即将执行的是哪种SQL语句了,然后委托给SqlSession进行执行了。该类里有两个内部类SqlCommand和MethodSignature。 SqlCommand用来封装CRUD操作,也就是我们在xml中配置的操作的节点,每个节点都会生成一个MappedStatement类。MethodSignature用来封装接口方法的参数以及返回类型。

 public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    // command是内部类SqlCommand的实例
    switch (command.getType()) {
      case INSERT: {
        // method是内部类MethodSignature的实例
        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()) {
          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;
  }

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐