0

I am using the JdbcTemplate. What i want to do is insert a record into the database however the primary key for the table is set to auto increment so i wont have to insert a value, how can i retrieve the id once i complete the insert?. Is there a simple way to do this or do i need to do another query to select it?

Example Of Jdbc Insert

Here the citizenId is autogenerated

 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");
4

2 回答 2

2

See 12.2.8: Retrieving auto generated keys:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html

于 2013-03-31T00:14:40.290 回答
2

just give you the example code, in case that link is broken. See it:

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
于 2013-03-31T00:29:28.950 回答