这是一个完整的示例(在 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)
| 归档时间: |
|
| 查看次数: |
4415 次 |
| 最近记录: |