Search code examples
javareactive-programmingdtoproject-reactorspring-data-r2dbc

Reactor : How to convert a Flux of entities into a Flux of DTO objects


I have a User entity and a Role entity. The fields are not important other than the fact that the User entity has a role_id field that corresponds to the id of its respective role. Since Spring Data R2DBC doesn't do any form of relations between entities, I am turning to the DTO approach. I am very new to R2DBC and reactive programming as a whole and I cannot for the life of me figure out how to convert the Flux<User> my repository's findAll() method is returning me to a Flux<UserDto>. My UserDto class is extremely simple :

@Data
@RequiredArgsConstructor
public class UserDto 
{
    private final User user;

    private final Role role;
}

Here is the UserMapper class I'm trying to make :

@Service
@RequiredArgsConstructor
public class UserMapper 
{
    private final RoleRepository roleRepo;

    public Flux<UserDto> map(Flux<User> users)
    {
        //???
    }
}

How can I get this mapper to convert a Flux<User> into a Flux<UserDto> containing the user's respective role?

Thanks!


Solution

  • Assuming your RoleRepository has a findById() method or similar to find a Role given its ID, and your user object has a getRoleId(), you can just do it via a standard map call:

    return users.map(u -> new UserDto(u, roleRepo.findById(u.getRoleId())));
    

    Or in the case where findById() returns a Mono:

    return users.flatMap(u -> roleRepo.findById(u.getRoleId()).map(r -> new UserDto(u, r)));
    

    You may of course want to add additional checks if it's possible that getRoleId() could return null.