Getting a Page of DTO objects from Spring Data repository

David Moreno García picture David Moreno García · Dec 19, 2014 · Viewed 9.3k times · Source

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?

Answer

lusoAlex picture lusoAlex · Mar 4, 2015

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