Is it possible to get the @@identity from the SQL insert on a Spring jdbc template call? If so, how?
TIA
Is it possible to get the @@identity from the SQL insert on a Spring jdbc template call? If so, how?
TIA
I don't know if there is a "one-liner" but this seems to do the trick (for MSSQL at least):
// -- call this after the insert query...
this._jdbcTemplate.queryForInt( "select @@identity" );
Decent article here.
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