0

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

1 回答 1

1

您可以使用JdbcTemplate运行完整的插入 SQL 。您可以在此处提供您想要的任何 SQL,为您的插入定义尽可能少或多的列,只要您的表的 DDL 允许。

这个答案更详细地介绍了这一点。

于 2016-04-20T13:05:29.363 回答