MyBatis印象阅读之StatementHandler解析

在上一章关于Executor的解析中,我们留下了关于StatementHandler的疑问,下面我们就对这个类进行分析。

1. StatementHandler源码分析

看到这个类,你可能会和原生的Statement联想起来,下面我们先来看下这个接口的方法有哪些:

public interface StatementHandler {

  /**
   * 准备操作,可以理解成创建 Statement 对象
   *
   * @param connection         Connection 对象
   * @param transactionTimeout 事务超时时间
   * @return Statement 对象
   */
  Statement prepare(Connection connection, Integer transactionTimeout)
      throws SQLException;

  /**
   * 设置 Statement 对象的参数
   *
   * @param statement Statement 对象
   */
  void parameterize(Statement statement)
      throws SQLException;

  /**
   * 添加 Statement 对象的批量操作
   *
   * @param statement Statement 对象
   */
  void batch(Statement statement)
      throws SQLException;

  /**
   * 执行写操作
   *
   * @param statement Statement 对象
   * @return 影响的条数
   */
  int update(Statement statement)
      throws SQLException;

  /**
   * 执行读操作
   *
   * @param statement Statement 对象
   * @param resultHandler ResultHandler 对象,处理结果
   * @param  泛型
   * @return 读取的结果
   */
   List query(Statement statement, ResultHandler resultHandler)
      throws SQLException;

  /**
   * 执行读操作,返回 Cursor 对象
   *
   * @param statement Statement 对象
   * @param  泛型
   * @return Cursor 对象
   */
   Cursor queryCursor(Statement statement)
      throws SQLException;

  BoundSql getBoundSql();

  ParameterHandler getParameterHandler();

}

再来看下继承关系:

StatementHandler子类继承图

1.1 RoutingStatementHandler类解析

我们先来看下用来路由的RoutingStatementHandler类,他的逻辑比较清晰:

public class RoutingStatementHandler implements StatementHandler {

  private final StatementHandler delegate;

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

  }

  @Override
  public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
    return delegate.prepare(connection, transactionTimeout);
  }

 

我们就看到这个逻辑根据ms.getStatementType()来路由,方法的话套路太多,不做所有展示。

myBatis也是老套路,实现了一个抽象类,包含了一些通常的操作:
我们来看下BaseStatementHandler的属性和构造方法:

1.2 BaseStatementHandler源码解析

public abstract class BaseStatementHandler implements StatementHandler {

  protected final Configuration configuration;
  protected final ObjectFactory objectFactory;
  protected final TypeHandlerRegistry typeHandlerRegistry;
  protected final ResultSetHandler resultSetHandler;
  protected final ParameterHandler parameterHandler;

  protected final Executor executor;
  protected final MappedStatement mappedStatement;
  protected final RowBounds rowBounds;

  protected BoundSql boundSql;

  protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    this.configuration = mappedStatement.getConfiguration();
    this.executor = executor;
    this.mappedStatement = mappedStatement;
    this.rowBounds = rowBounds;

    this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
    this.objectFactory = configuration.getObjectFactory();

    if (boundSql == null) { // issue #435, get the key before calculating the statement
      generateKeys(parameterObject);
      boundSql = mappedStatement.getBoundSql(parameterObject);
    }

    this.boundSql = boundSql;

    this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
    this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
  }
 }

这里关于parameterHandler和resultSetHandler的技术债之后再讲,我们先看这里的generateKeys方法:
这里的generateKeys方法为:

  protected void generateKeys(Object parameter) {

    KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
    ErrorContext.instance().store();
    //获得自增主键,放入到parameter
    keyGenerator.processBefore(executor, mappedStatement, null, parameter);
    ErrorContext.instance().recall();
  }

这里又让我们欠下了关于KeyGenerator的技术债,之后我们重点来看下它的方法:

  @Override
  public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
    ErrorContext.instance().sql(boundSql.getSql());
    Statement statement = null;
    try {
      // 创建 Statement 对象交给子类实现
      statement = instantiateStatement(connection);
      // 设置超时时间
      setStatementTimeout(statement, transactionTimeout);
      // 设置 fetchSize
      setFetchSize(statement);
      return statement;
    } catch (SQLException e) {
      closeStatement(statement);
      throw e;
    } catch (Exception e) {
      closeStatement(statement);
      throw new ExecutorException("Error preparing statement.  Cause: " + e, e);
    }
  }

这里最主要的一个创建Statement的方法instantiateStatement又交给了子类去实现。我们来看SimpleStatementHandler的实现。

1.3 SimpleStatementHandler的instantiateStatement方法

// SimpleStatementHandler.java

@Override
protected Statement instantiateStatement(Connection connection) throws SQLException {
    if (mappedStatement.getResultSetType() == ResultSetType.DEFAULT) {
        return connection.createStatement();
    } else {
        return connection.createStatement(mappedStatement.getResultSetType().getValue(),  ResultSet.CONCUR_READ_ONLY);
    }
}

就是我们传统上的创建statement,也到了我们MyBatis封装的最底层。我们再来看下PreparedStatementHandler类的实现。

1.4 PreparedStatementHandler的instantiateStatement方法

  @Override
  protected Statement instantiateStatement(Connection connection) throws SQLException {
    String sql = boundSql.getSql();
    if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
      String[] keyColumnNames = mappedStatement.getKeyColumns();
      if (keyColumnNames == null) {
        return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
      } else {
        return connection.prepareStatement(sql, keyColumnNames);
      }
    } else if (mappedStatement.getResultSetType() == ResultSetType.DEFAULT) {
      return connection.prepareStatement(sql);
    } else {
      return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
    }
  }

是不是也非常的熟悉?

剩下的就是关于传统PrepareStatement和Statement如何操作数据库的CRUD了,我们抽一个方法来看下。

1.5 PreparedStatementHandler的query方法

  @Override
  public  List query(Statement statement, ResultHandler resultHandler) throws SQLException {
    PreparedStatement ps = (PreparedStatement) statement;
    ps.execute();
    return resultSetHandler.handleResultSets(ps);
  }

这里唯一不同的是先执行execute方法,在通过resultHandler去解析返回值。

2. 今日总结

今天我们看了关于StatementHandler的源码分析,得知了这个类的作用是用来创建对应的Statement的,并且操作数据库的CRUD与解析工作,一块最低层的内容就被我们啃下了。但是今天我们也欠下了3个技术债:

parameterHandler
resultSetHandler
KeyGenerator

在之后的章节中我们再来分析~~~

你可能感兴趣的:(MyBatis印象阅读之StatementHandler解析)