开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜