mybatis一次查询过程的分析 一

使用方法有两种,第一种直接使用sqlsession进行查询操作,第二种生成mapper接口的动态代理。第二种会用到第一种过程,我们直接看第二种。mapper的动态代理类是MapperProxy
在这里插入图片描述
之前启动过程中已经分析过了,invoke方法
在这里插入图片描述
最终会执行到mapperMethod的execute方法,一个mapper接口对应一个MapperProxy,里面的一个方法对应一个MapperMethod,直接看execute方法

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);
        }
        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;

先看执行sql的类型如果是查询,在看当前method的返回类型,如果是list就调用
sqlSession.selectList(command.getName(), param, rowBounds);如果是单个则调用sqlSession.selectOne
这里的sqlsession默认实现是DefaultSqlSession。
在这里插入图片描述
从这里可以看出selectOne也是调用selectList。
直接看selectList方法
在这里插入图片描述
mybatis核心的查询逻辑都在这里了。下面挨个分析

猜你喜欢

转载自blog.csdn.net/zhenghuangyu/article/details/86722890