Spring JDBC和复合主键

Dam*_*ien 5 java spring jdbc

在Spring jdbc中,有没有一种方法可以在插入行时返回复合主键。该复合主键由来自不同序列的值组成

任何帮助是极大的赞赏

问候达米安

Geo*_*uba 4

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

我的桌子:

CREATE TABLE test
(
  id serial NOT NULL,
  otherid serial NOT NULL,
  val text,
  CONSTRAINT test_pkey PRIMARY KEY (id, otherid)
)
Run Code Online (Sandbox Code Playgroud)

这是您取回钥匙的方法:

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");
}
Run Code Online (Sandbox Code Playgroud)

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

JdbcTemplate 使用 ColumnMapRowMapper 来映射生成的键(生成的键作为结果集返回,至少在 PostgreSQL 上是这样。它实际上返回整行,就好像您在刚刚插入的行上执行 select 一样)。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;
    }

}
Run Code Online (Sandbox Code Playgroud)