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
  • 27,328
  • 49
  • 143
  • 192

2 Answers2

3

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

leonbloy
  • 73,180
  • 20
  • 142
  • 190
1

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

sojin
  • 4,527
  • 2
  • 37
  • 40