【问题标题】:Add value to a Mono<Entity> with Spring WebFlux使用 Spring WebFlux 为 Mono<Entity> 添加价值
【发布时间】:2022-01-02 18:14:51
【问题描述】:

我需要将属性Friends(这是一个ArrayList)从Mono&lt;PersonEntity&gt; 复制到Mono&lt;UserEntity&gt;(数据库中没有Friends 属性),但我没有找到正确的方法这样做,所以当我将 Mono&lt;UserEntity&gt; 映射到 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) 之后添加一些东西,但我尝试过的一切都没有奏效。 感谢您的宝贵时间

【问题讨论】:

    标签: java spring mapping spring-webflux


    【解决方案1】:

    由于您没有显示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 中阅读更多相关信息。

    【讨论】:

    • 谢谢,它适用于您的解决方案和对 Dto 的一些调整
    • 不客气!
    猜你喜欢
    • 2020-04-30
    • 2021-07-14
    • 1970-01-01
    • 2018-12-12
    • 2021-11-18
    • 2019-05-18
    • 2020-05-18
    • 2021-11-09
    • 2021-09-30
    相关资源
    最近更新 更多