java - spring jdbc 和复合主键

标签 java spring jdbc

spring jdbc 有没有办法在插入行时返回复合主键。 这个复合主键由来自不同序列的值组成

非常感谢任何帮助

问候 达米安

最佳答案

这是一个完整的例子(在 PostgreSQL 8.4 上测试过):

我的 table :

CREATE TABLE test
(
  id serial NOT NULL,
  otherid serial NOT NULL,
  val text,
  CONSTRAINT test_pkey PRIMARY KEY (id, otherid)
)

这是你取回 key 的方式:

public void doStuff() {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(
            new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement("insert into test(val) values (?)", Statement.RETURN_GENERATED_KEYS);
                    ps.setInt(1, 42);
                    return ps;
                }
            },
            keyHolder);

    keyHolder.getKeys().get("id");
    keyHolder.getKeys().get("otherid");
}

现在,如果您想直接从 keyHolder 中获取作为某个类的实例的组合键,这并不简单。

JdbcTemplate 使用 ColumnMapRowMapper 来映射生成的键(生成的键作为结果集返回,至少在 PostgreSQL 上是这样。它实际上返回整行,就像您在刚刚插入的行上执行选择一样)。 JdbcTemplate 中的许多其他地方使用了相同的 ColumnMapRowMapper。

这里唯一可能的扩展点是 KeyHolder 本身。以下是您可以执行的操作:

public void doStuff() {
    CompositeKeyHolder keyHolder = new CompositeKeyHolder();
    ... same code here ...

    keyHolder.getCompositeKey();
}


class CompositeKeyHolder extends GeneratedKeyHolder {
    private boolean converted;

    public CompositeKey getCompositeKey() {
        return new CompositeKey((Integer)this.getKeys().get("id"), (Integer)this.getKeys().get("otherid"));
    }
}


class CompositeKey {

    private Integer id;

    private Integer otherId;

    CompositeKey(Integer id, Integer otherId) {
        this.id = id;
        this.otherId = otherId;
    }

    public Integer getId() {
        return id;
    }

    public Integer getOtherId() {
        return otherId;
    }

}

关于java - spring jdbc 和复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3133699/

相关文章:

java - 带有 MyBatis 错误的 Spring MVC 4。

java - SQL 命令在 servlet 中未正确结束

sql - postgres准备语句中的几个关闭占位符

java - 当拖动超出其列表末尾时,如何防止 JList 选择元素?

java - JComboBoxes - 使用 setModel 访问对象(在 Swing 中)

java - 在 spring security 中禁用浏览器身份验证对话框

java - Spring Boot AOP 不适用于 AfterThrow

java - 在 Java 中的另一个数据映射器中使用数据映射器?

java - Wicket 口和 CSS 资源

java - 将自定义 View 添加到 xml 布局