Spring利用GeneratedKeyHolder,提供了一个可以返回新增记录对应主键值的方法: int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder)。
public Permission createPermission(final Permission permission) {
final String sql = "insert into sys_permissions(permission, 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, permission.getPermission());
psst.setString(2, permission.getDescription());
psst.setBoolean(3, permission.getAvailable());
return psst;
}
}, keyHolder);
permission.setId(keyHolder.getKey().longValue());
return permission;
}
相对来说,还是很好用的。