StatementHandler接口是MyBatis核心接口之一,它完成了MyBatis最核心的工作。
StatementHandler接口中的功能很多,例如创建Statement对象,为SQL语句绑定实参,执行select、insert、update、delete等多种类型的SQL语句,批量执行SQL语句,将结果集映射成结果对象。
StatementHandler接口的定义如下:
public interface StatementHandler {
// 从连接中获取一个Statement
Statement prepare(Connection connection, Integer transactionTimeout)
throws SQLException;
// 参数绑定
void parameterize(Statement statement)
throws SQLException;
// 批量执行
void batch(Statement statement)
throws SQLException;
// 执行update、insert、delete操作
int update(Statement statement)
throws SQLException;
// 执行select操作
<E> List<E> query(Statement statement, ResultHandler resultHandler)
throws SQLException;
<E> Cursor<E> queryCursor(Statement statement)
throws SQLException;
BoundSql getBoundSql();
ParameterHandler getParameterHandler();
}
MyBatis中提供了StatementHandler接口的多种实现类。
1.RoutingStatementHandler
RoutingStatementHandler会根据MappedStatement指定的statementTyp字段,创建对应的StatementHandler接口实现。RoutingStatementHandler类的具体实现如下:
public class RoutingStatementHandler implements StatementHandler {
// 封装的真正的StatementHandler对象
private final StatementHandler delegate;
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
// 根据MappedStatement的配置,生成一个对应的StatementHandler对象,并设置到delegate字段中
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());
}