我正在使用 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();