简体   繁体   中英

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 [].

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. Thanks for your time

Since you don't show PersonEntity and UserEntity we can only guess their properties and getter and setter methods. 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. You can read more about this in the reference documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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