天天看點

Mybatis源碼之Statement處理器RoutingStatementHandler(三)

RoutingStatementHandler類似路由器,在其構造函數中會根據Mapper檔案中設定的StatementType來選擇使用SimpleStatementHandler、PreparedStatementHandler和CallableStatementHandler,其實作的接口StatementHandler的方法也是由這三個具體實作類來實作。

/**
 * @author Clinton Begin
 */
//類似于路由器
public class RoutingStatementHandler implements StatementHandler {

  private final StatementHandler delegate;

  //選擇三種Statement,SimpleStatementHandler、PreparedStatementHandler和CallableStatementHandler
  public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }

  }

  //選中的Statement的操作
  public Statement prepare(Connection connection) throws SQLException {
    return delegate.prepare(connection);
  }

  public void parameterize(Statement statement) throws SQLException {
    delegate.parameterize(statement);
  }

  public void batch(Statement statement) throws SQLException {
    delegate.batch(statement);
  }

  public int update(Statement statement) throws SQLException {
    return delegate.update(statement);
  }

  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    return delegate.<E>query(statement, resultHandler);
  }

  public BoundSql getBoundSql() {
    return delegate.getBoundSql();
  }

  public ParameterHandler getParameterHandler() {
    return delegate.getParameterHandler();
  }
}