Spring JDBC-最后插入的ID


问题内容

我正在使用Spring JDBC。是使用Spring Framework获取最后插入的ID的简单方法,还是我需要使用一些JDBC技巧?

jdbcTemplate.update("insert into test (name) values(?)", params, types);
// last inserted id ...

我发现以下内容,但得到: 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();

问题答案:

旧的/标准方法是在插入(ref)之后使用调用
currval( )。简单安全。