KeyHolder holder = new GeneratedKeyHolder();
getJdbcTemplate().update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection)
throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql.toString(),
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, person.getUsername());
ps.setString(2, person.getPassword());
ps.setString(3, person.getEmail());
ps.setLong(4, person.getRole().getId());
return ps;
}
}, holder);
Long newPersonId = holder.getKey().longValue();
Lưu ý rằng trong các phiên bản Postgres mới hơn, bạn cần sử dụng
connection.prepareStatement(sql.toString(),
new String[] { "idcompte" /* name of your id column */ })
thay vì
connection.prepareStatement(sql.toString(),
Statement.RETURN_GENERATED_KEYS);