之前分析了SqlSessionFactory初始化,通过SqlSession获取UserMapper代理对象

debug打上断点在List<User> users = mapper.selectAll();

看下执行如何执行代理对象的方法

public class MybatisDemo {

    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.selectAll();
        System.out.println(users);
    }

}

1、debug进去发现是MapperProxy类的invoke方法,MapperProxy实现了InvocationHandler接口

public class MapperProxy<T> implements InvocationHandler, Serializable {
    ......
    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 (method.isDefault()) { // 判断是否java8接口默认方法
              if (privateLookupInMethod == null) {
                return invokeDefaultMethodJava8(proxy, method, args);
              } else {
                return invokeDefaultMethodJava9(proxy, method, args);
              }
            }
          } catch (Throwable t) {
            throw ExceptionUtil.unwrapThrowable(t);
        }
        final MapperMethod mapperMethod = cachedMapperMethod(method);
        return mapperMethod.execute(sqlSession, args);
    }
}

1)Method的类不是Obejct,也不是default方法,所以主要看下面两条语句

final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);

2)cachedMapperMethod方法主要是缓存MapperMethod ,如果不存在,则创建新对象保存到map中,如果已经存在则直接返回。

methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));

2、mapperMethod.execute(sqlSession, args); // 真正执行mapper方法

    2.1)判断是insert,update,select,delete方法

    2.2)由于是执行方法是查询user表中所有记录,所以是method.returnsMany()为true,

    执行result = executeForMany(sqlSession, args);返回结果

public Object execute(SqlSession sqlSession, Object[] args) {
  Object result;
  switch (command.getType()) {
    case INSERT: {
      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);
        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;
}

3、result = executeForMany(sqlSession, args);

private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
  List<E> result;
  // 转化sql参数
  Object param = method.convertArgsToSqlCommandParam(args);
  if (method.hasRowBounds()) {
    RowBounds rowBounds = method.extractRowBounds(args);
    result = sqlSession.selectList(command.getName(), param, rowBounds);
  } else {
     // 通过sqlSession执行查询列表 
    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;
}

    3.1)通过sqlSession执行查询列表调用栈

result = sqlSession.selectList(command.getName(), param);
  this.selectList(statement, parameter, RowBounds.DEFAULT);
    public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) 

    3.2)看下最后一个selectList方法,通过com.whf.mapper.UserMapper.selectAll从configuration对象的mappedStatements属性(Map)获取MappedStatement对象,MappedStatement之前分析过,保存了sql的相关信息。然后通过执行器executor执行sql

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  try {
    // 获取MappedStatement 
    MappedStatement ms = configuration.getMappedStatement(statement);
    // 通过executor执行sql
    return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}

    3.3)根据mappedStatement对象封装sql和参数信息到boundSql对象中,执行query方法

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
  // 封装sql和参数信息到boundSql对象中
  BoundSql boundSql = ms.getBoundSql(parameterObject);
  CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
  return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

4、委托SimpleExecutor执行query方法

    4.1)在doQuery方法中执行查询,带do开头的方法一般都是真正做事的,调用栈如下

delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
    list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);

    4.2)doQuery方法在prepareStatement方法内部生成Statement 对象,并且设置好sql参数,调用 handler.query(stmt, resultHandler); 去查询数据库

public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  Statement stmt = null;
  try {
    // 从mappedStaement对象获取configuration对象 
    Configuration configuration = ms.getConfiguration();
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    // 准备Statement对象
    stmt = prepareStatement(handler, ms.getStatementLog());
    return handler.query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}

    4.3)将Statement转换成PreparedStatement,在ps.execute(); 执行sql,最终在resultSetHandler.handleResultSets(ps);解析ResultSet返回查询结果

public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
  PreparedStatement ps = (PreparedStatement) statement;
  ps.execute();
  return resultSetHandler.handleResultSets(ps);
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐