Search code examples
javasql-serverspringjdbcjdbctemplate

identity from sql insert via jdbctemplate


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


Solution

  • 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