Is it possible to get the @@identity from the SQL insert on a Spring jdbc template call? If so, how?
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
How about SimpleJdbcInsert.executeAndReturnKey? It takes two forms, depending on the input:
Map
public java.lang.Number executeAndReturnKey(java.util.Map<java.lang.String,?> args)Description copied from interface:
SimpleJdbcInsertOperationsExecute the insert using the values passed in and return the generated key. This requires that the name of the columns with auto generated keys have been specified. This method will always return a
KeyHolderbut the caller must verify that it actually contains the generated keys.Specified by:
executeAndReturnKeyin interfaceSimpleJdbcInsertOperationsParameters:
args - Map containing column names and corresponding valueReturns:
the generated key value
SqlParameterSource
public java.lang.Number executeAndReturnKey(SqlParameterSourceparameterSource)Description copied from interface:
SimpleJdbcInsertOperationsExecute the insert using the values passed in and return the generated key. This requires that the name of the columns with auto generated keys have been specified. This method will always return a
KeyHolderbut the caller must verify that it actually contains the generated keys.Specified by:
executeAndReturnKeyin interfaceSimpleJdbcInsertOperationsParameters:
parameterSource - SqlParameterSource containing values to use for insertReturns:
the generated key value.
Adding detailed notes/sample code to todd.pierzina answer
jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
jdbcInsert.withTableName("TABLE_NAME").usingGeneratedKeyColumns(
"Primary_key");
Map<String, Object> parameters = new HashMap<>();
parameters.put("Column_NAME1", bean.getval1());
parameters.put("Column_NAME2", bean.getval2());
// execute insert
Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(
parameters));
// convert Number to Int using ((Number) key).intValue()
return ((Number) key).intValue();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With