MyBatis之StatementHandler简析

StatementHandler

StatementHandler就是Statement的处理器,Executor是委托给StatementHandler处理数据库的CRUD操作。例如Executor的query方法,其实调用的handler.query方法,调用前会调用handler取到Java中的Statement实例。

public List doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {

Statement stmt = null;

Configuration configuration = ms.getConfiguration();

StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);

stmt = prepareStatement(handler, ms.getStatementLog());

return handler.query(stmt, resultHandler);

}

先看下接口StatementHandler的方法,一共八个方法,前几个方法都会调用Statement的对应方法。

StatementHandler

再看下StatementHandler的实现类,RoutingStatementHandler,SimpleStatementHandler,PreparedStatementHandler和CallableStatementHandler,默认是PreparedStatementHandler。

StatementHandler实现类

看Executor中生成Statementhandler的地方会发现使用的是RoutingStatementHandler。然而RoutingStatementHandler又会根据StatementType创建真正的Statementhandler。

StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameterObject, rowBounds, resultHandler, boundSql);

/** 创建一个StatementHandler */

public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);

statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);

return statementHandler;

}

为了验证StatementHandler会调用Statement的相应方法,我们看看PreparedStatementHandler中的update方法,代码如下:

public int update(Statement statement) throws SQLException {

PreparedStatement ps = (PreparedStatement) statement;

ps.execute();

int rows = ps.getUpdateCount();

Object parameterObject = boundSql.getParameterObject();

KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();

keyGenerator.processAfter(executor, mappedStatement, ps, parameterObject);

return rows;

}

下文简析ResultSetHandler......

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20200220A0T4JI00?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

扫码关注云+社区

领取腾讯云代金券