You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebFlux中调用Repository方法后Date字段未更新的问题求助

WebFlux中异步操作未执行导致字段不更新的问题解决

问题核心原因

你的代码存在两个关键问题:

  1. 异步操作未触发:在map中调用repository.existsByNumberThing()后,没有将这个Mono<Boolean>串联到反应式流中。WebFlux的反应式操作是懒加载的,仅创建Mono实例而不整合到流里,内部的setDate1/setDate2代码永远不会执行。
  2. 类型不兼容:直接替换map为flatMap时,未正确处理返回值类型,导致repository.save()的方法引用无法匹配。

修正后的代码

public Mono<Void> createThings(Flux<Thing> things) {
    return things
            .map(mapper::toEntity)
            .map(ThingEntity::onCreate)
            // 用flatMap替代map,处理异步查询操作
            .flatMap(thingEntity -> {
                // 同步设置dateTruc字段
                if (thingEntity.getSomething() != null && thingEntity.getSomething().equals("truc")) {
                    thingEntity.setDateTruc(LocalDate.now());
                }
                // 执行异步存在性查询,并在查询完成后设置date1/date2
                return repository.existsByNumberThing(thingEntity.getNumberThing())
                        .map(exists -> {
                            thingEntity.setDate1(Boolean.TRUE.equals(exists) ? LocalDateTime.now() : null);
                            thingEntity.setDate2(Boolean.TRUE.equals(exists) ? null : LocalDateTime.now());
                            return thingEntity;
                        });
            })
            .flatMap(repository::save)
            .doOnError(error -> log.error("Error : ", error))
            .then(); // then()直接返回Mono<Void>,替代冗余的then(Mono.empty())
}

关键修正点说明

  • 替换map为flatMap:repository.existsByNumberThing()返回Mono<Boolean>,属于异步操作,必须用flatMap将这个异步流嵌入到主流程中,确保查询完成后再执行字段设置和后续保存操作。
  • 串联异步操作:将字段设置逻辑放在existsByNumberThing()返回的Mono的map中,保证只有当异步查询完成后,才会更新date1和date2字段,并且将处理后的实体返回给下一个流节点。
  • 简化返回值:then()方法会等待所有流元素处理完成后返回Mono<Void>,完全符合方法的返回类型,无需额外调用Mono.empty()。

内容的提问来源于stack exchange,提问作者MiKa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 20:38:12