通过JdbcTemplate.update()方法将KeyHolder传进来,经过一系列操作,由PreparedStatement.getGeneratedKeys()获取主键,并将值注入到KeyHolder中(注意:通过KeyHolder获取插入主键方法,仅在jdbc 3.0才被支持)
具体源码如下:
public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException {
int rows = ps.executeUpdate();List> generatedKeys =generatedKeyHolder.getKeyList();generatedKeys.clear();ResultSet keys = ps.getGeneratedKeys();if (keys != null) {
try {
RowMapperResultSetExtractor> rse =new RowMapperResultSetExtractor>(getColumnMapRowMapper(), 1);generatedKeys.addAll(rse.extractData(keys));
}finally {JdbcUtils.closeResultSet(keys);}
}
if (logger.isDebugEnabled()) {
logger.debug("SQL update affected " + rows + " rows and returned " + generatedKeys.size() + " keys");
}
return rows;
}