Mybatis_SQL执行流程解析

主流程

大体流程:
方法代理MapperProxy->会话SQLSession->执行器Executor->声明处理器StatementHandler/JDBC
在这里插入图片描述

具体流程以查询为例:

MapperProxy#invoke

MapperProxy用于实现动态代理,是InvocationHandler接口的实现类。与MyBatis交互的门面,存在的目的是为了方便调用,本身不会影响执行逻辑。

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   
  try {
   
    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);
  }
  final MapperMethod mapperMethod = cachedMapperMethod(method);
  //这里
  return mapperMethod.execute(sqlSession, args);
}

MapperMethod#execute

将定义的接口方法转换成MappedStatement对象

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

DefaultSqlSession#selectOne

@Override
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.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;
  }
}

DefaultSqlSession#selectList

@Override
public <E> List<E> selectList(String statement, Object parameter) {
   
  return this.selectList(statement, parameter, RowBounds.DEFAULT);
}
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
   
  try {
   
    MappedStatement ms = configuration.getMappedStatement(statement);
    //这里
    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();
  }
}

CachingExecutor#query

二级缓存执行器,这里没有用到

@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
    throws SQLException {
   
  Cache cache = ms.getCache();
  //如果有缓存
  if (cache != null) {
   
    flushCacheIfRequired(ms);
    if (ms.isUseCache() && resultHandler == null) {
   
      ensureNoOutParams(ms, boundSql);
      @SuppressWarnings("unchecked")
      List<E> list = (List) tcm.getObject(cache, key);
      if (list == null) {
   
        list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
        tcm.putObject(cache, key, list); // issue #578 and #116
      }
      return list;
    }
  }
  //没有缓存,这里
  return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

BaseExecutor#query

抽像类,基础执行器,包括一级缓存逻辑在此实现

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++;
    list = resultHandler == null ? (List) 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;
}

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

SimpleExecutor#doQuery

@Override
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();
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    //这里
    stmt = prepareStatement(handler, ms.getStatementLog());
    //执行查询
    return handler.query(stmt, resultHandler);
  } finally {
   
    closeStatement(stmt);
  }
}

SimpleExecutor#prepareStatement

private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
   
  Statement stmt;
  //获取连接
  Connection connection = getConnection(statementLog);
  //预处理SQL
  stmt = handler.prepare(connection, transaction.getTimeout());
  //设置参数
  handler.parameterize(stmt);
  return stmt;
}

MySQL select语句的执行流程

在这里插入图片描述

会话SqlSession

创建SqlSession

DefaultSqlSessionFactory实例化的SqlSession

  • 重载的创建SqlSession 的方法
@Override
public SqlSession openSession() {
   
  return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
/**
* 是否自动提交
*/
@Override
public SqlSession openSession(boolean autoCommit) {
   
  return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, autoCommit
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值