Spring利用GeneratedKeyHolder,提供了一个可以返回新增记录所对应的主键值的方法:

int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder)

Spring为KeyHolder接口指代了一个通用的实现类GeneratedKeyHolder,该类返回新增记录时的自增长主键值。假设我们希望在新增论坛板块对象后,希望将主键值加载到对象中,则可以按以下代码进行调整:

 public Role createRole(final Role Role) {
final String sql = "insert into sys_roles(role, description, available) values(?,?,?)"; GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement psst = connection.prepareStatement(sql, new String[] { "id" });
psst.setString(1, Role.getRole());
psst.setString(2, Role.getDescription());
psst.setBoolean(3, Role.getAvailable());
return psst;
}
}, keyHolder);
Role.setId(keyHolder.getKey().longValue()); return Role;
}
05-11 08:15