【问题标题】:Batch insert in kotlin with spring-fu使用 spring-fu 在 kotlin 中批量插入
【发布时间】:2020-01-17 08:43:46
【问题描述】:

我看了这个例子:

https://github.com/spring-projects/spring-fu/blob/cb7c60eae7c022fe066cfe8bf7fbfb752b9dd64b/samples/kofu-coroutines-r2dbc/src/main/kotlin/com/sample/Repositories.kt#L26

suspend fun save(user: User)=
    client.insert().into<User>().table("users").using(user).await()

这很好用。我想使用批量插入方法:

https://docs.spring.io/spring-data/r2dbc/docs/1.0.x/reference/html/#reference,第 11.7.2 节。插入数据

使用 (Publisher) 用于接受要插入的对象流。

所以我尝试了:

client.insert().into<User>().table("users").using(Flux.fromIterable(user)).await()

但这并没有做任何事情。为什么会这样?应该如何编写才能工作?

【问题讨论】:

  • 我认为您的意思是第 13.7.2 节。插入数据。在您的示例中,我假设您在 Flux.fromIterable(user) 中的用户是用户列表?我还发现 using(Publisher) 不像记录的那样工作。我读到“使用(Publisher):接受要插入的对象流。”因为将插入流中的所有对象。我的流中只有一个对象被插入到我的 PostgreSQL 数据库中,而不是我已转换为该方法的流的列表中的所有对象。我正在使用 io.r2dbc-postgresql 0.8.0.BUILD-SNAPSHOT 和 spring-boot-starter-data-r2dbc 0.1.0.BUILD-SNAPSHOT

标签: spring-boot kotlin r2dbc


【解决方案1】:

我刚刚意识到,您没有包含 fetch() 方法来让 DatabaseClient 在 using() 方法之后插入对象。

client.insert()
    .into<User>()
    .table("users")
    .using(Flux.fromIterable(user))
    .fetch()
    .await()

正如我在上面的评论中提到的,我的批量插入只是在流中插入第一个对象。根据发布者的DatabaseClient.InsertSpec,在调用 RowsFetchSpec.one() 或 RowsFetchSpec.first() 时,提取只插入一个对象。这导致我在 fetch() 方法之后添加 .all() 以获取要插入的所有对象,在您的情况下是

client.insert()
    .into<User>()
    .table("users")
    .using(Flux.fromIterable(user))
    .fetch()
    .all()
    .await()

你的和我的批量插入唯一的区别是我使用的是 Java 并且我使用了 into(Class table) 方法而不是 into(String table) 并定义了 @Table 和 @Id 并带有注释用户 POJO。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2018-05-17
    • 2018-07-18
    • 1970-01-01
    • 2012-03-31
    • 2014-11-14
    • 1970-01-01
    相关资源
    最近更新 更多