Mybatis源码解析(3) 代理类的select()方法分析

1 查询功能
User user = mapper.selectByID(1);

2 调用代理类的invoke()方法
  • 类 : MapperProxy
  • 方法 : invoke()
  • 作用 : 被代理类调用方法时,都会执行代理类的involve()方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	//查询调用方法是否是object方法,如:equals().hashcode()...
    if (Object.class.equals(method.getDeclaringClass())) {
      try {
      	//如果为object方法,那么执行原方法
        return method.invoke(this, args);
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    }
    //为接口定义方法,先从缓存中拿MapperMethod对象
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

private MapperMethod cachedMapperMethod(Method method) {
	//从缓存中获取MapperMethod 对象,没有则创建后放入缓存中
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }

3 看下 MapperMethod 对象创建过程
  • 类 : MapperMethod
  • 方法 : 构造器
  • 作用 : 一个MapperMethod 对象对应该条sql语句,并根据 Configuration对象中封装的 MappedStatement 对象为其封装sql信息与方法的映射
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
	//sql指令(内部类): 获取该方法对应该条sql的指令+方法完全限定名
    this.command = new SqlCommand(config, mapperInterface, method);
    //方法签名(内部类): 获取该条方法的入参,结果集,参数类型等参数信息
    this.method = new MethodSignature(config, mapperInterface, method);
  }

4 回到2中的12行 mapperMethod.execute() 方法
  • 类:
  • 方法 :
  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);
          //返回Map集合
        } else if (method.returnsMap()) {
          result = executeForMap(sqlSession, args);
        } else if (method.returnsCursor()) {
          result = executeForCursor(sqlSession, args);
        } else {
          //获取请求参数
          Object param = method.convertArgsToSqlCommandParam(args);
          //将方法完全限定名+参数,传递给sqlSession
          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;
  }

5 方法被传入到SqlSession中执行
  • 类 : DefaultSqlSession
  • 方法 : selectOne()
  • 作用 : 查询单一结果方法
public class DefaultSqlSession implements SqlSession {
  //配置对象
  private Configuration configuration;
  //执行器
  private Executor executor;
  //是否开启自动提交
  private boolean autoCommit;
  private boolean dirty;
  private List<Cursor<?>> cursorList;
  
public <T> T selectOne(String statement, Object parameter) {
    // Popular vote was to return null on 0 results and throw exception on too many.
    List<T> list = this.<T>selectList(statement, parameter);
    if (list.size() == 1) {
      return list.get(0);
    } else if (list.size() > 1) {
      throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
    } else {
      return null;
    }
  }
  /**
  	statement:方法完全限定名
  	parameter:参数
  	rowBounds:mybatis自带分页功能(内存分页,不推荐)
  */
 public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      //根据方法名找到对应的MappedStatment
      MappedStatement ms = configuration.getMappedStatement(statement);
      /**
      	wrapCollection : 确定参数集合类型,并以map集合的实行告知集合形式
      	参数是collection集合 : 返回map(key:"collection",value:parameter)
      	参数是list集合 : 	  返回map(key:"list",value:parameter)
      	参数是array集合 : 	  返回map(key:"array",value:parameter)
      	参数不是集合		:	  返回原 object 
      */
      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();
    }
  }

6 在Executor上加一层缓存功能
  • 类 : CachingExecutor
  • 方法 : query
  • 作用 : 此处使用了装饰器模式,为Executor对象加了缓存功能,根据该方法创建缓存秘钥,再次调用此方法时,判断秘钥是否匹配并进行一级缓存获取
public class CachingExecutor implements Executor {
 //执行器接口
  private Executor delegate;
  private TransactionalCacheManager tcm = new TransactionalCacheManager();
  //装饰器模式
  public CachingExecutor(Executor delegate) {
    this.delegate = delegate;
    delegate.setExecutorWrapper(this);
  }
//查询方法
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
	//获取绑定sql, 将#{parameter} 替换成 ? 
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    //根据参数构建 缓存Key ,一级缓存的标识秘钥,根据这几个参数判断是否是同一个sql
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    //执行查查询方法
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }
/**
	查询方法
*/
 public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
     //引用<cache>标签时,使用
    Cache cache = ms.getCache();
    if (cache != null) {
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, parameterObject, boundSql);
        @SuppressWarnings("unchecked")
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

7 跟踪query()方法,看下真正执行查询的方法
  • 类 : BaseExecutor
  • 方法 : query()
  • 作用 : 真正执行查询的方法
private static final Log log = LogFactory.getLog(BaseExecutor.class);

  protected Executor wrapper;
  //一级缓存map集合
  protected PerpetualCache localCache;
  protected PerpetualCache localOutputParameterCache;
  protected Configuration configuration;
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List<E> list;
    try {
      queryStack++;
      //根据缓存密码key去本地一缓存中查询是否有该key
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      //一级缓存中存在,从缓存中加载
      if (list != null) {
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
      //一级缓存中没有,从数据库中查询后放入缓存中
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }

8 一级缓存中没有改sql,从数据库中查询,Jdbc API
  • 类 : BaseExecutor
  • 方法 : queryFromDatabase()
  • 作用 : 从数据库中查询
 private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    //先用该秘钥在一级缓存中占位置
    localCache.putObject(key, EXECUTION_PLACEHOLDER);
    try {
      //执行查询功能
      list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    } finally {
    //从一级缓存中移除该占位符
      localCache.removeObject(key);
    }
    //在一级缓存中加入该查询结果
    localCache.putObject(key, list);
    if (ms.getStatementType() == StatementType.CALLABLE) {
      localOutputParameterCache.putObject(key, parameter);
    }
    return list;
  }

9 查看执行查询功能doquery()方法
  • 类 : SimpleExecutor
  • 方法 : doQuery()
  • 作用 : 执行查询功能
 public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
      Configuration configuration = ms.getConfiguration();
      //获取执行statement对象的执行器
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      //创建prepareStatement对象
      stmt = prepareStatement(handler, ms.getStatementLog());
      //使用执行器执查询,并返回处理后的结果集
      return handler.<E>query(stmt, resultHandler);
    } finally {
      //关闭资源
      closeStatement(stmt);
    }
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值