Before refactoring, I was inserting a row into the db using jdbcTemplate, preparedStatementCreator and a GeneratedKeyHolder to store the generated id of the inserted row.
Generated keys may be returned with JdbcTemplate#update(PreparedStatementCreator,KeyHolder) method. But to achieve this you need to change your request, based on org.springframework.jdbc.core.PreparedStatementCreatorFactory.
Instead I would recommend to use for inserting SimpleJdbcInsert utility class.
If your DB fields are the very same as your entities' fields, then you can simply do as following:
Number key = jdbcInsert.executeAndReturnKey(new BeanPropertySqlParameterSource(entity));
//set generated key
if (key != null){
entity.setId(key.longValue());
}
If it is not (as in your case), then
//define parameters
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("FIRSTNAME", pupil.getFirstname());
parameters.put("SURNAME", pupil.getSurname());
parameters.put("GIVEN_NAME", pupil.getGivenName());
parameters.put("DOB", pupil.getDob());
//execute insert
Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(parameters));
//set generated key
if (key != null){
pupil.setId(key.longValue());
}
jdbcInsert
parameter you need to define once for each entity, and it will look like the following:
SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(getJdbcTemplate());
jdbcInsert.withTableName(entityName); //e.g. "STUDENTS"
jdbcInsert.setGeneratedKeyName(idColumn); //e.g. "ID"
jdbcInsert.setColumnNames(columnNames); //e.g. Arrays.asList("FIRSTNAME", "SURNAME", "GIVEN_NAME", "DOB")