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/