I would like to retrieve the auto-generated id from a row insertion, but I get a NullPointerException
Here is the code :
long result = 0
I had the same problem and it turned out that my table ID was not auto incrementing.
Take a look at this post, especially the accepted answer of using the INSERT...RETURNING syntax:
How to get a value from the last inserted row?
This the best way to get this value in PostgreSQL as you only make one network round trip and it's done as a single atomic operation on the server.
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();
Note that in newer versions of Postgres you need to use
connection.prepareStatement(sql.toString(),
new String[] { "idcompte" /* name of your id column */ })
instead of
connection.prepareStatement(sql.toString(),
Statement.RETURN_GENERATED_KEYS);