来自sql insert的身份通过jdbctemplate [英] identity from sql insert via jdbctemplate
本文介绍了来自sql insert的身份通过jdbctemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在Spring jdbc模板调用中从SQL插入中获取@@ identity?如果是这样,怎么做?
Is it possible to get the @@identity from the SQL insert on a Spring jdbc template call? If so, how?
推荐答案
JDBCTemplate.update
方法重载获取一个名为GeneratedKeyHolder的对象,您可以使用它来检索自动生成的密钥。例如(代码取自此处):
The JDBCTemplate.update
method is overloaded to take an object called a GeneratedKeyHolder which you can use to retrieve the autogenerated key. For example (code taken from here):
final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps =
connection.prepareStatement(INSERT_SQL, new String[] {"id"});
ps.setString(1, name);
return ps;
}
},
keyHolder);
// keyHolder.getKey() now contains the generated key
这篇关于来自sql insert的身份通过jdbctemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文