I am using Spring Data JPA and I have a PagingAndSortingRepository<Contact, Long>
that uses a JPASpecificationExecutor<Contact>
. I pass a Specification
and a Pageable
instance to the .findAll()
method of this repository to get a Page<Contact>
.
However, my Contact
entity has a lot of extra fields and mappings that I don't need on my front end. So, I have a ContactDto
that contains only the necessary fields, and I have a method that can convert from Contact
to ContactDto
.
private ContactDto convertToContactDto(Contact contact) {
//do the conversion
}
How would I go about using this conversion method to convert the Page<Contact>
to a Page<ContactDto>
?
I can get the content of the Page<Contact>
and do the conversion like this.
final Page<Contact> contactPage = pagingAndSortingContactRepository
.findAll(ContactSpecification.findByFirstNmLike(firstNm), pageable);
final Collection<ContactDto> contactDtos = contactPage.getContent()
.stream()
.map(this::convertToContactDto)
.collect(Collectors.toList());
But then I am left with a Collection
instead of a Page
, and I don't know how to get that Collection
into the content of the Page
. Is there a way to do this? Or is there another way to call the conversion on the Page<Contact>
instance itself?
It may be the case that a Page transformation is less efficient to perform iteratively, as
Page.map(..)
is likely to do, than with the entire collection in hand.In this case we can use Spring's
PageExecutionUtils
to do the messy work of reconstructing a page with the transformed content.Turns out that
Page
has its own.map()
method, to which you can pass a method reference to do the conversion.Here is how I ended up doing the conversion.
The
convertToContactDto
method simply creates and returns an instance of the class I'm trying to convert to: