标签:
Spring利用GeneratedKeyHolder,提供了一个可以返回新增记录对应主键值的方法:int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder).
Spring为KeyHolder接口指代了一个通用的实现类GeneratedKeyHolder,该类返回新增记录时的自增长主键值。假设我们希望在新增论坛板块对象后,希望将主键值加载到对象中,则可以按以下代码进行调整:
1 final String INSERT_SQL = "insert into gtable(username,callback) values(?,?)"; 2 KeyHolder keyHolder = new GeneratedKeyHolder(); 3 jdbcTemplate.update(new PreparedStatementCreator() { 4 public PreparedStatement createPreparedStatement( 5 Connection connection) throws SQLException { 6 PreparedStatement ps = connection.prepareStatement(INSERT_SQL, 7 new String[] { "id" }); 8 ps.setString(1, request.getUsername()); 9 ps.setString(2, request.getCallback()); 10 return ps; 11 } 12 }, keyHolder); 13 logger.debug("id:" + keyHolder.getKey()+"long:"+keyHolder.getKey().longValue());
标签:
原文地址:http://www.cnblogs.com/snn0605/p/5913513.html