简体   繁体   中英

Spring MVC Retrieving Database Autogenerated PrimaryKey For Record After INSERT Record

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM