简体   繁体   English

为 Mono 增值<entity>与 Spring WebFlux</entity>

[英]Add value to a Mono<Entity> with Spring WebFlux

I need to copy the property Friends (which is an ArrayList) from a Mono<PersonEntity> to a Mono<UserEntity> (which has not Friends property in the database), but I don't find the correct way to do it, so when i map the Mono<UserEntity> to Dto, the field Friends result to be an empty array [].我需要将属性Friends (这是一个 ArrayList)从Mono<PersonEntity>Mono<UserEntity> (在数据库中没有Friends属性),但我找不到正确的方法,所以当我 map 将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);
}

I think I should add something after findById(id) but everything i tried until now didn't work.我想我应该在findById(id)之后添加一些东西,但是到目前为止我尝试的一切都没有奏效。 Thanks for your time谢谢你的时间

Since you don't show PersonEntity and UserEntity we can only guess their properties and getter and setter methods.由于您没有显示PersonEntityUserEntity ,我们只能猜测它们的属性以及 getter 和 setter 方法。 Still, something along the following lines should work:尽管如此,以下几行的东西应该可以工作:

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);
}

The important thing is zipWith , which combines the result from a Mono and another Mono into a Tuple2 that you can then easily map.重要的是zipWith ,它将Mono和另一个Mono的结果组合成一个Tuple2 ,然后您可以轻松地 map。 You can read more about this in the reference documentation .您可以在参考文档中阅读更多相关信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM