Spring JDBC-最后插入的ID [英] Spring JDBC - Last inserted id
本文介绍了Spring JDBC-最后插入的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Spring JDBC。是使用Spring Framework获取最后插入的ID的简单方法,还是我需要使用一些JDBC技巧?
I'm using Spring JDBC. Is a simple way to get last inserted ID using Spring Framework or i need to use some JDBC tricks ?
jdbcTemplate.update("insert into test (name) values(?)", params, types);
// last inserted id ...
我发现以下内容,但得到了: org.postgresql.util.PSQLException:不支持返回自动生成的密钥。
I found something like below, but i get: org.postgresql.util.PSQLException: Returning autogenerated keys is not supported.
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(
Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("insert into test (name) values(?)", new String[] {"id"});
ps.setString(1, "test");
return ps;
}
}, keyHolder);
lastId = (Long) keyHolder.getKey();
推荐答案
旧方法/标准方法是使用呼叫 currval() 后插入(< a href = http://neilconway.org/docs/sequences/ rel = nofollow>参考)。简单又安全。
The old/standard way is to use call currval() after the insert (ref). Simple and secure.
这篇关于Spring JDBC-最后插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文