63

Is it possible to get the @@identity from the SQL insert on a Spring jdbc template call? If so, how?

javamonkey79
  • 17,443
  • 36
  • 114
  • 172

4 Answers4

102

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
Jason Gritman
  • 5,251
  • 4
  • 30
  • 38
52

How about SimpleJdbcInsert.executeAndReturnKey? It takes two forms, depending on the input:

(1) The input is a Map

public java.lang.Number executeAndReturnKey(java.util.Map<java.lang.String,?> args)

Description copied from interface: SimpleJdbcInsertOperations

Execute 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 KeyHolder but the caller must verify that it actually contains the generated keys.

Specified by:

executeAndReturnKey in interface SimpleJdbcInsertOperations

Parameters:

args - Map containing column names and corresponding value

Returns:

the generated key value

(2) The input is a SqlParameterSource

public java.lang.Number executeAndReturnKey(SqlParameterSourceparameterSource)

Description copied from interface: SimpleJdbcInsertOperations

Execute 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 KeyHolder but the caller must verify that it actually contains the generated keys.

Specified by:

executeAndReturnKey in interface SimpleJdbcInsertOperations

Parameters:

parameterSource - SqlParameterSource containing values to use for insert

Returns:

the generated key value.

Sadeq Dousti
  • 3,346
  • 6
  • 35
  • 53
todd.pierzina
  • 740
  • 4
  • 10
28

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();
Peter Szanto
  • 7,568
  • 2
  • 51
  • 53
Sheetal Mohan Sharma
  • 2,908
  • 1
  • 23
  • 24
3

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.

javamonkey79
  • 17,443
  • 36
  • 114
  • 172
  • 3
    Page not found with the link. – Ruslan May 09 '17 at 12:02
  • 1
    For SQL Server, @@identity returns the last id generated on any table in the database in the current session. So for example if your insert causes a trigger to fire that also generates a new identity in some table, you'll get that value. In a majority of cases you never want to use @@identity. – Rick Oct 01 '18 at 15:49