简体   繁体   English

使用 Spring Data R2DBC 进行批量插入时检索生成的 ID

[英]Retrieve generated IDs when doing bulk insert using Spring Data R2DBC

I have a scenario where my table has an autogenerated id column and I need to bulk insert items into db and fetch the generated ids .我有一个场景,我的表有一个自动生成的 id 列,我需要将项目批量插入 db 并获取生成的 ids Is there any way I can achieve that?有什么办法可以实现吗?

This is my table:这是我的表:

CREATE TABLE test_table (
  `id` SERIAL NOT NULL,
  `name` VARCHAR(100) NOT NULL,
  `created_date` DATETIME NOT NULL,
  PRIMARY KEY (`id`)
);

To save a list of items into this table, the code I am using:要将项目列表保存到此表中,我使用的代码是:

String initialSql = "INSERT INTO test_table(`name`,`created_date`) VALUES ";

    List<String> values =
        dummyEntities.stream()
            .map(dummyEntity -> "('" + dummyEntity.getName() + "','"
                + dummyEntity.getCreatedDate().atZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime().toString() + "')")
            .collect(Collectors.toList());

    String sqlToExecute =  initialSql + String.join(",", values);
    client.execute(sqlToExecute)
             .//Then what?

The generated SQL statement (from DEBUG Logs):生成的 SQL 语句(来自 DEBUG Logs):

2020-09-15 18:59:32.613 DEBUG 44801 --- [actor-tcp-nio-1] o.s.d.r2dbc.core.DefaultDatabaseClient   : Executing SQL statement [INSERT INTO test_table(`name`,`created_date`) VALUES ('Abhi57','2020-09-15T13:29:29.951964'),('Abhi92','2020-09-15T13:29:29.952023')]

I even tried using ConnectionFactory , still no clue我什至尝试使用ConnectionFactory ,仍然没有线索

    Mono.from(connectionFactory.create())
        .map(Connection::createBatch)
        .map(batch -> {
          dummyEntities.forEach(dummyEntity -> {
            String sql = String.format("INSERT INTO `test_table` (`name`,`created_date`) VALUES ('%s','%s');", dummyEntity.getName(),
                dummyEntity.getCreatedDate().atZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime().toString());
            batch.add(sql);
          });
          return batch;
        })
        .flatMap(batch -> Mono.from(batch.execute()))
        .//Then what?

For reference, dummyEntities variable holds a list of DummyEntity objects.作为参考, dummyEntities变量包含一个DummyEntity对象列表。 And the DummyEntity class looks like this: DummyEntity类如下所示:

@Table("test_table")
public class DummyEntity implements Persistable<Long> {

  @Id
  @Column("id")
  private Long id;

  @Column("name")
  private String name;

  @Column("created_date")
  private OffsetDateTime createdDate;

  //Getter,Setter
  @Override
  public boolean isNew() {
    return id == null;
  }
}

Dependencies used: 2.3.2.RELEASE使用的依赖项:2.3.2.RELEASE

    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    implementation 'org.springframework.boot:spring-boot-starter-data-r2dbc'
    implementation 'dev.miku:r2dbc-mysql:0.8.2.RELEASE'

Using the original ConnectionFacotory is easy to get generated ids.使用原始的ConnectionFacotory很容易获得生成的 id。

I have tried to use ConnectionFactory to get the generated ids, worked as expected.我尝试使用ConnectionFactory来获取生成的 id,按预期工作。

                    .thenMany(
                            Mono.from(conn)
                                    .flatMapMany(
                                            c -> c.createStatement(insertSql)
                                                    .returnGeneratedValues("id")
                                                    .execute()

                                    )
                    )
                    .flatMap(data -> Flux.from(data.map((row, rowMetadata) -> row.get("id"))))
                    .doOnNext(id -> log.info("generated id: {}", id))

The complete code example is here .完整的代码示例在这里

It prints logs in the console like this.它像这样在控制台中打印日志。

2020-09-19 10:43:30,815 INFO [main] com.example.demo.H2Tests$Sql:89 generated id: 1
2020-09-19 10:43:30,815 INFO [main] com.example.demo.H2Tests$Sql:89 generated id: 2

And I think the new DatabaseClient in Spring framework 5.3 is just a thin wrapper of the connectionfactories,and use a filter to get generated ids.而且我认为 Spring 框架 5.3 中的新DatabaseClient只是连接工厂的薄包装,并使用filter来获取生成的 id。

databaseClient.sql("INSERT INTO  posts (title, content, metadata) VALUES (:title, :content, :metadata)")
.filter((statement, executeFunction) -> statement.returnGeneratedValues("id").execute())

Check the complete example codes (but this example only retrieve a single id).检查完整的示例代码(但此示例仅检索单个 ID)。

Later response, but since i faced the same issue on R2DBC PostgreSQL, here is a possible solution:后来的回应,但由于我在 R2DBC PostgreSQL 上遇到了同样的问题,这里是一个可能的解决方案:

// -- generate 100 Product entities and mark them as CREATE
// -- Product is implementing Persistable<UUID> and isNew() will return TRUE for CREATE and FALSE for UPDATE 
List<Product> list = Stream.generate(() -> Product.builder()
    .articleNumber(UUID.randomUUID().toString().substring(0, 10))
    .name(UUID.randomUUID().toString())
    .images(Arrays.asList("1", "2"))
    .saveAction(SaveAction.CREATE)
    .build()).limit(100).collect(Collectors.toList());

// -- create the PostgresqlBatch and return the Result flux
Flux<? extends Result> flux = databaseClient.inConnectionMany(connection -> {
  Batch batch = connection.createBatch();

  list.forEach(p -> {
    batch.add("INSERT INTO product(\"id\",\"article_number\",\"name\") VALUES ('" + p.getId() + "','" + p.getArticleNumber() + "','" + p
        .getName() + "') RETURNING id, name, article_number");
  });

  return Flux.from(batch.execute());
});

// -- transform the Result flux into a Product flux
return flux.flatMap(result -> result.map((row, rowMetadata) -> Product.builder()
    .id(row.get("id", UUID.class))
    .name(row.get("name", String.class))
    .articleNumber(row.get("article_number", String.class))
    .build()));

The secret is RETURNING column1, column2, column3 added to each insert statement.秘密是添加到每个插入语句中的RETURNING column1、column2、column3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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