这是一个完整的例子(在 PostgreSQL 8.4 上测试):
我的桌子:
CREATE TABLE test
(
id serial NOT NULL,
otherid serial NOT NULL,
val text,
CONSTRAINT test_pkey PRIMARY KEY (id, otherid)
)
这是您取回密钥的方式:
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 上。它实际上返回整行,就好像您在刚刚插入的行上执行选择一样)。相同的 ColumnMapRowMapper 用于 JdbcTemplate 中的许多其他地方。
这里唯一可能的扩展点是 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;
}
}