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();
0

2 Answers 2

3

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

1
  • Thanks. I did it this way: jdbcTemplate.queryForLong("select currval('main_seq')");
    – marioosh
    Apr 19, 2011 at 6:39
1

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.