2011-04-18 8 views
1

私はSpring JDBCを使用しています。 Spring Frameworkを使用して最後に挿入されたIDを取得する簡単な方法ですか、いくつかのJDBCトリックを使用する必要がありますか?Spring JDBC - 最後に挿入されたID

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

私は以下のようなものを見つけました、しかし、私は得る: "PreparedStatementsのために生成されたキー" の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(); 

答えて

3

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

+0

ありがとうございました。私はこうしました: 'jdbcTemplate.queryForLong(" currval( 'main_seq')を選択してください); ' – marioosh

1

サポートは唯一のPostgreSQL版8.4-701以来始めました。

+0

ありがとう、ありがとうございました。 – marioosh

関連する問題