如何仅使用自动生成的值和 return ID 向 spring 中的数据库插入一行?

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

我使用 spring 框架,并想在数据库中插入一行以获得其 ID,这是进一步处理所需要的。 下面给出了插入查询,这是一个简单的查询,没有参数。但更糟糕的是,如何使用 SimpleJdbcInsert 中的 executeAndReturnKey 构造工作调用?这是插入的 SQL 查询。但是我不知道是否可以在 simpleJdbcInsert 个实例中使用它。

insert into sdc_import_run(id_import_run, create_date)
values(nextval('seq_import_run'),now())

我试过了

Number genId = simpleJdbcInsert.withTableName("sdc_import_run")
            .usingGeneratedKeyColumns("id_import_run")
            .executeAndReturnKey(new MapSqlParameterSource());

它不起作用,问题是,他们想要 table 的所有参数,但我不需要它们中的任何一个,我只想插入自动生成的:id_import_run(主键)和 create_date。因此,我想在变量中插入 ID。你会怎么做?

编辑 这种方法很有效。

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

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

This answer 更详细地介绍了这一点。