介绍
四大对象:executor, statementHandler,parameterHandler,resultHandler对象。
statementHandler是四大对象中最重要的一个,它的功能是使用parameterHandler为我们绑定Sql参数,然后和数据库对话,然后使用resultHandler对象 组装最后的结果返回。
下面主要分一下StatementHandler一些接口,创建,便于了解StatementHanderl在mybatis操作数据库时中的作用
statementHandler 接口
在源码中statementHandler是一个接口
public interface StatementHandler {
Statement prepare(Connection connection, Integer transactionTimeout)
throws SQLException;
void parameterize(Statement statement)
throws SQLException;
void batch(Statement statement)
throws SQLException;
int update(Statement statement)
throws SQLException;
<E> List<E> query(Statement statement, ResultHandler resultHandler)
throws SQLException;
<E> Cursor<E> queryCursor(Statement statement)
throws SQLException;
BoundSql getBoundSql();
ParameterHandler getParameterHandler();
}
接口有4个实现类和一个基础类:
- RoutingStatementHandler,这是一个封装类,它不提供具体的实现,只是根据Executor的类型,创建不同的类型StatementHandler。
SimpleStatementHandler,这个类对应于JDBC的Statement对象,用于没有预编译参数的SQL的运行。
PreparedStatementHandler 这个用于预编译参数SQL的运行。
CallableStatementHandler 它将实存储过程的调度。
基础类(有点类似BaseExecutor模式):
- BaseStatementHandler:上面除了RoutingStatementHandler以外,其他三个类都继承该类。
StatementHandler创建
Mybatis的Configuration的进行查询或者更新时会创建RoutingStatementHandler(创建方法在 如下代码中)。
Configuration.java
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
throws SQLException {
Statement stmt = null;
try {
...
//这里调用创建StatementH