简体   繁体   中英

How to insert a row to DB in spring, using only auto-generated values, and return an ID?

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);
}

You could run your complete insert SQL using JdbcTemplate . You can provide any SQL you'd like here, with as little or many columns defined for your insert as your table's DDL will allow.

This answer covers this in more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM