聊聊Mybatis的BaseStatementHandler的三个子类
今天我们继续聊StatementHandler的实现类
PreparedStatementHandler
PreparedStatementHandler处理的是包含?占位符的sql语句,所以它需要进行参数绑定:
@Override
public void parameterize(Statement statement) throws SQLException {
parameterHandler.setParameters((PreparedStatement) statement);
}
我们通过parameterize()方法的实现就能看出,这个方法是设置参数的,而其他的方法和和StatementHandler整体差不多
SimpleStatementHandler
SimpleStatementHandler对没有占位符的sql语句的StatementHandler类,看一下它的update()方法的实现:
对于insert update delete语句都会执行这个方法
public int update(Statement statement) throws SQLException {
String sql = boundSql.getSql();
Object parameterObject = boundSql.getParameterObject();
KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
int rows;
if (keyGenerator instanceof Jdbc3KeyGenerator) {
statement.execute(sql, Statement.RETURN_GENERATED_KEYS);
rows = statement.getUpdateCount();
keyGenerator.processAfter(executor, mappedStatement, statement, parameterObject);
} else if (keyGenerator instanceof SelectKeyGenerator) {
statement.execute(sql);
rows = statement.getUpdateCount();
keyGenerator.processAfter(executor, mappedStatement, statement, parameterObject);
} else {
statement.execute(sql);
rows = statement.getUpdateCount();
}
return rows;
}
- 获取到sql
- 获取KeyGenerator实例,如果是Jdbc3KeyGenerator实例,调用execute(sql, Statement.RETURN_GENERATED_KEYS)方法执行sql,如果是SelectKeyGenerator,调用execute(sql)执行sql,然后执行keyGenerator.processAfter()方法将主键存入MappedStatement对象中
- 通过getUpdateCount()方法获取影响行数并返回
有的同学会产生疑问,为什么没有调用keyGenerator.processBefore()方法呢?其实在BaseStatementHandler的构造方法中就产生调用了
对于查询方法就更简单了,获取sql调用statement.execute(sql)进行执行,然后resultSetHandler.handleResultSets(statement)进行结果处理,返回list集合
CallableStatementHandler
@Override
public int update(Statement statement) throws SQLException {
CallableStatement cs = (CallableStatement) statement;
cs.execute();
int rows = cs.getUpdateCount();
Object parameterObject = boundSql.getParameterObject();
KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
keyGenerator.processAfter(executor, mappedStatement, cs, parameterObject);
resultSetHandler.handleOutputParameters(cs);
return rows;
}