我正在使用JdbcTemplate。我想要做的是将一条记录插入数据库,但是表的主键设置为自动增量,所以我不必插入一个值,一旦完成插入,我怎样才能检索id?有没有一种简单的方法可以做到这一点,还是我需要做另一个查询来选择它?
Jdbc插入示例
这里citizenId是自动生成的
public void saveCitizen(Citizens citizen) {
logger.debug("In saveCitizens");
int count = getJdbcTemplate().update("INSERT INTO crimetrack.tblcitizens (citizenId,fName,lName,oName,photo,countryId,addLn1, addLn2, addLn3,"
+"genderId,ethnicityId, skinColorId, eyeColorId,hairColorId,occupationId,"
+"phoneNo, maritalStatusId, noticableFeatures,weight,height,citizenTypeId,dob)"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
, new Object[]{citizen.getfName(),citizen.getlName(),citizen.getoName(),
citizen.getPhoto(),citizen.getCountryId(),citizen.getAddLn1(),
citizen.getAddLn2(),citizen.getAddLn3(),citizen.getGenderId(),
citizen.getEthnicityId(),citizen.getSkinColorId(),citizen.getEyeColorId(),
citizen.getHairColorId(),citizen.getOccupationId(),citizen.getPhoneNo(),
citizen.getMaritalStatusId(),citizen.getNoticeableFeatures(),
citizen.getWeight(),citizen.getHeight(),citizen.getCitizenTypeId(),
citizen.getDob()});
logger.info(count +" Rows affected in tblCitizens");
答案 0 :(得分:2)
参见12.2.8:检索自动生成的密钥:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html
答案 1 :(得分:2)
只是提供示例代码,以防链接断开。看到它:
final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps =
connection.prepareStatement(INSERT_SQL, new String[] {"id"});
ps.setString(1, name);
return ps;
}
},
keyHolder);
// keyHolder.getKey() now contains the generated key