使用 Spring WebFlux 为 Mono<Entity> 添加值

Add value to a Mono<Entity> with Spring WebFlux

我需要将 属性 Friends(这是一个 ArrayList)从 Mono<PersonEntity> 复制到 Mono<UserEntity>(没有 Friends属性 在数据库中),但我找不到正确的方法,所以当我将 Mono<UserEntity> 映射到 Dto 时,字段 Friends 结果是一个空数组 [] .

public Mono<Dto> findEntityByIdAndLabel(Long id, String label) {
    return getPersonByIdAndLabel(id, label).flatMap(person -> {
         return UserRepository.findByID(id);     
    })
            .switchIfEmpty(Mono.error(new EntityNotFoundException(entity.toString(), id.toString(), label)))
            .map(this::mapper);
}

我想我应该在 findById(id) 之后添加一些内容,但我到目前为止所做的一切都没有奏效。 感谢您的宝贵时间

由于您没有显示 PersonEntityUserEntity 我们只能猜测它们的属性以及 getter 和 setter 方法。不过,按照以下几行应该可以工作:

public Mono<Dto> findEntityByIdAndLabel(Long id, String label) {
    return getPersonByIdAndLabel(id, label)
        .zipWith(UserRepository.findByID(id))
        .map(tuple -> {
            List friends = tuple.getT1().getFriends();
            UserEntity user = tuple.getT2():
            user.setFriends(friends);
            return user;
        })
        .switchIfEmpty(Mono.error(new EntityNotFoundException(entity.toString(), id.toString(), label)))
        .map(this::mapper);
}

重要的是 zipWith,它将 Mono 和另一个 Mono 的结果组合成 Tuple2,然后您可以轻松映射。您可以在 reference documentation.

中阅读更多相关信息