我有一个List<Order>
(或者Flux<Order>
如果我想要的话)每个Order
元素都有一个List<Item>
. 我想使用spring-data-r2dbc
(因此ReactiveCrudRepository
)和spring-webflux
. 这两个表都有外键约束,所以Order
必须在其s之前插入 an。Item
事务处理是另一个主题,超出了这个问题的范围。应用程序该部分的返回类型应该是 a Flux<Order>
,因为它将是 REST 响应的返回值。
问题是如何“组合” aMono<Order>
和它的Flux<Item>
.
我已经研究过压缩,但我无法让它工作(见下面注释掉的代码)。此外,我很确定拉链不是正确的事情,因为我一侧有一个,另一侧有n。我也试过.doOnSuccess
了,但这也导致Flux<Item>
没有终端操作。
SomeService.kt
fun saveOrders(orders: List<Order>): Flux<Order> {
// the flatMap (and flatMapMany below) with side effect isn't that nice either
return Flux.fromIterable(orders).flatMap { saveOrder(it) }
}
private fun saveOrder(order: Order): Mono<Order> {
val soonToBeSavedOrder: Mono<Order> = orderRepository.save(order)
val soonTeBeSavedItems: Flux<Item> = soonToBeSavedOrder.flatMapMany { saveItems(it) }
// TODO: how to "combine" the Mono and the Flux because the Flux doesn't
// have a terminal operation that way and therefore saveItems is never called.
return soonToBeSavedOrder
}
private fun saveItems(order: Order): Flux<Item> {
return itemRepository.saveAll(order.items)
}
订单.kt
class Order(
id: UUID,
var someData: String,
@Transient
val items: MutableList<Item> = ArrayList()) : Persistable<UUID> {
@Id
private var id: UUID = id
override fun getId(): UUID { return id }
override fun isNew(): Boolean { return true }
}
项目.kt
class Item(
id: UUID,
var someData: String) : Persistable<UUID> {
@Id
private var id: UUID = id
override fun getId(): UUID? { return id }
override fun isNew(): Boolean { return true }
}