如何使用Spring Jdbctemplate.update(String sql,obj ... args)获取插入的ID [英] How to get inserted id using Spring Jdbctemplate.update(String sql, obj...args)
问题描述
我正在使用Jdbctemplate,并且需要插入查询的ID. 我读到我必须构建一个特定的PreparedStatement并使用GeneratedKeyHolder对象.
I'm using Jdbctemplate and I need the inserted id of a query. I read that I have to build a particular PreparedStatement and use GeneratedKeyHolder object.
问题在于,在我的应用程序中,所有inserts方法都使用此JdbcTemplate更新方法:
The problem is that in my application all inserts method uses this JdbcTemplate update method:
getJdbcTemplate().update(SQL_INSERT,param1,param2,param3,...);
还有另一种方法来获取插入的ID,而无需重构所有的dao吗?
Is there another way to get the inserted id without refactoring all daos?
推荐答案
查看 JdbcTemplate 您有两种选择:
使用NamedParameterJdbcTemplate
的使用JdbcTemplate
的还有其他一些可用方法,这些方法将填充给定
There are also some other methods available which will populate the keys to the given GeneratedKeyHolder, it's up to you which one suits your needs.
编辑
例如使用JdbcTemplate:
For e.g. using JdbcTemplate:
GeneratedKeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement("INSERT INTO SOME_TABLE(NAME, VALUE) VALUES (?, ?) ", Statement.RETURN_GENERATED_KEYS);
statement.setString(1, "SomeName");
statement.setString(2, "SomeValue");
return statement;
}
}, holder);
long primaryKey = holder.getKey().longValue();
这篇关于如何使用Spring Jdbctemplate.update(String sql,obj ... args)获取插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!