1

I'm using 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();
marioosh
  • 25,903
  • 44
  • 135
  • 187

2 Answers2

3

The old/standard way is to use call currval() after the insert (ref). Simple and secure.

leonbloy
  • 69,336
  • 20
  • 133
  • 185
1

Support for "generated keys for PreparedStatements" started only since PostgreSql Ver 8.4-701.

sojin
  • 4,356
  • 2
  • 35
  • 40