Spring JDBC - Last inserted id

你。 提交于 2019-12-01 10:57:08

问题


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

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/5703281/spring-jdbc-last-inserted-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!