I use spring framework, and would like to insert a row to DB in order to have its ID, which is needed for further processing.
Inserting query is given below, it's a simple query, without parameters. But it's even worse, cause how to construct working call using executeAndReturnKey
from SimpleJdbcInsert
? This is an SQL query for insert. But I don't know whether it is possible to use it within simpleJdbcInsert
instance.
insert into sdc_import_run(id_import_run, create_date)
values(nextval('seq_import_run'),now())
I tried
Number genId = simpleJdbcInsert.withTableName("sdc_import_run")
.usingGeneratedKeyColumns("id_import_run")
.executeAndReturnKey(new MapSqlParameterSource());
It doesn't work, the thing is, they want all parameters for the table, but I dont want any of them, I want to insert only auto-generated: id_import_run
(primary key) and create_date
. As a result I want to have the inserted ID in a variable. How would you do that?
EDIT Such an approach works fine.
public Integer persistInsertImportRunForId(){
String queryString = getSql("insertImportRunForId");
KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(con -> {
return con.prepareStatement(queryString, Statement.RETURN_GENERATED_KEYS);
}, holder
);
return CommonUtils.tryOrGet(() -> holder.getKeys().get("id_import_run"), null);
}