identity from sql insert via jdbctemplate

javamonkey79 picture javamonkey79 · Nov 3, 2009 · Viewed 59.7k times · Source

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

Answer

Jason Gritman picture Jason Gritman · Nov 3, 2009

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