When I hit the database with PagingAndSortingRepository.findAll(Pageable)
I get Page
. However, I want to expose DTO\'s to the clien
I am created and using solution with model mapper, generics and lambdas for common usage.
/**
* Maps the Page {@code entities} of T
type which have to be mapped as input to {@code dtoClass} Page
* of mapped object with D
type.
*
* @param - type of objects in result page
* @param - type of entity in entityPage
* @param entities - page of entities that needs to be mapped
* @param dtoClass - class of result page element
* @return page - mapped page with objects of type D
.
* @NB dtoClass
must has NoArgsConstructor!
*/
public Page mapEntityPageIntoDtoPage(Page entities, Class dtoClass) {
return entities.map(objectEntity -> modelMapper.map(objectEntity, dtoClass));
}
This is exactly the case which you need (and I think common case for wide range of other cases).
You already have the data obtained from repository (same is with service) on this way:
Page entities = objectEntityRepository.findAll(pageable);
Everything what you need for conversion is to call this method on this way:
Page dtoPage = mapEntityPageIntoDtoPage(entities, ObjectDto.class);
@Tip: You can use this method from util class, and it can be reused for all entity/dto in Page conversions on services and controllers according to your architecture.
Example:
Page dtoPage = mapperUtil.mapEntityPageIntoDtoPage(entities, ObjectDto.class);