Mybatis源码之Statement处理器RoutingStatementHandler(三)

时间:2022-04-14 09:22:16

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