I'm trying to basically do nested loops with reactive/spring webflux. How would I go about iterating through a Flux, fetching child records, and ultimately return a Flux of DTOs (with the child records in each user dto)?
Here's the gist of it, although probably still way off.
public Flux<UserDTO> getUsers(String name) {
Flux<User> users = userRepo.findByNameLike(name);
return users.flatMap(u -> {
Flux<Phone> phoneNumbers = phoneNumberRepo.findByUserId(u.getUserId());
return phoneNumbers;
}).flatMap(r -> {
UserDto userDto = new UserDto();
userDto.setUserId(u.getUserid());
userDto.setPhoneNumbers(phoneNumbers);
return userDto;
});
}
CodePudding user response:
you need to use map instead of flatMap on transfer to dto
CodePudding user response:
You should collect the child entities to list before mapping.
public Flux<UserDto> getUsers(String name) {
Flux<User> users = userRepo.findByNameLike(name);
return users.flatMap(u -> phoneNumberRepo.findByUserId(u.getUserId())
.collectList()
.map(phoneNumbers -> {
UserDto userDto = new UserDto();
userDto.setUserId(u.getUserId());
userDto.setPhoneNumbers(phoneNumbers);
return userDto;
}));
}