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