【问题标题】:Spring JDBC - Last inserted idSpring JDBC - 最后插入的 id
【发布时间】:2011-08-07 21:05:41
【问题描述】:

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

【问题讨论】:

    标签: postgresql spring-mvc jdbctemplate spring-jdbc


    【解决方案1】:

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

    【讨论】:

    • 谢谢。我是这样做的:jdbcTemplate.queryForLong("select currval('main_seq')");
    【解决方案2】:

    仅从 PostgreSql Ver 8.4-701 开始支持“为 PreparedStatements 生成密钥”。

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 2012-08-14
      • 2011-03-28
      • 2011-05-13
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      相关资源
      最近更新 更多