Search code examples
springspring-datadto

Getting a Page of DTO objects from Spring Data repository


I'm trying to use DTOs in a Spring project to decouple business and presentation but I'm having problems while retrieving data from the Spring Data repository. Here I have a sample code:

public Page<UserDto> findAll(int pageIndex) {
    return userRepository.findAll(createPageable(pageIndex)); // Page<User>
}

As you can see, I'm trying to return a page of UserDto but I'm getting a page of User.

How can I do this?


Solution

  • You can do it like this :

    public Page<UserDto> findAll(Pageable p) {
        Page<User> page = userRepository.findAll(p); // Page<User>
        return new PageImpl<UserDto>(UserConverter.convert(page.getContent()), p, page.getTotalElements());
    }