标签:
Spring利用GeneratedKeyHolder,提供了一个可以返回新增记录所对应的主键值的方法:
int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder)
Spring为KeyHolder接口指代了一个通用的实现类GeneratedKeyHolder,该类返回新增记录时的自增长主键值。假设我们希望在新增论坛板块对象后,希望将主键值加载到对象中,则可以按以下代码进行调整:
1 public Role createRole(final Role Role) { 2 final String sql = "insert into sys_roles(role, description, available) values(?,?,?)"; 3 4 GeneratedKeyHolder keyHolder = new GeneratedKeyHolder(); 5 jdbcTemplate.update(new PreparedStatementCreator() { 6 @Override 7 public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { 8 PreparedStatement psst = connection.prepareStatement(sql, new String[] { "id" }); 9 psst.setString(1, Role.getRole()); 10 psst.setString(2, Role.getDescription()); 11 psst.setBoolean(3, Role.getAvailable()); 12 return psst; 13 } 14 }, keyHolder); 15 Role.setId(keyHolder.getKey().longValue()); 16 17 return Role; 18 }
标签:
原文地址:http://www.cnblogs.com/vinozly/p/4853284.html