Spring JDBC - Last inserted id
I'm using开发者_JAVA百科 Spring JDBC. Is a simple way to get last inserted ID using Spring Framework or i need to use some JDBC tricks ?
jdbcTemplate.update("insert into test (name) values(?)", params, types);
// last inserted id ...
I found something like below, but i get: org.postgresql.util.PSQLException: Returning autogenerated keys is not supported.
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(
Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("insert into test (name) values(?)", new String[] {"id"});
ps.setString(1, "test");
return ps;
}
}, keyHolder);
lastId = (Long) keyHolder.getKey();
The old/standard way is to use call currval() after the insert (ref). Simple and secure.
Support for "generated keys for PreparedStatements" started only since PostgreSql Ver 8.4-701.
精彩评论