simpleJdbcTemplate. - insert and retrieve ID

Sebastian picture Sebastian · Feb 10, 2010 · Viewed 20.2k times · Source

I'm putting the data into database with simpleJdbcTemplate.

simpleJdbcTemplate.update("insert into TABLE values(default)");

I dont want to put any data because i dont need it for my unit test purpose.

How can i get the id from the inserted row? I can retriev the current sequence value but if somebody else will do a insert then i will be get a next sequence value.

Is there any way to use simpleJdbcTemplate to insert a row and get id? The update method retuns the number of inserted rows and i would like to have the id. Thank you for your help.

Answer

George picture George · Feb 11, 2011

Did you find the answer yet? If not, try to use SimpleJdbcInsert instead. For example:

SimpleJdbcInsert sji = new SimpleJdbcInsert(dataSource)
    .withTableName(TableName)
    .usingColumns(new String[]{your columns})
    .usingGeneratedKeyColumns(you auto-increment id colums);

then retrieve

sji.executeAndReturnKey(args).longValue();