1

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

2 に答える 2

3

古い/標準的な方法は、挿入 ( ref ) の後に call currval()を使用することです。シンプルで安全。

于 2011-04-18T14:58:48.233 に答える
1

「PreparedStatements の生成されたキー」のサポートは、PostgreSql Ver 8.4-701以降で開始されました。

于 2011-04-18T14:48:56.973 に答える