I have created a solution with model mapper, generics and lambdas for common usage, and it is used on a daily basis on several projects.
/**
* Maps the Page {@code entities} of <code>T</code> type which have to be mapped as input to {@code dtoClass} Page
* of mapped object with <code>D</code> type.
*
* @param <D> - type of objects in result page
* @param <T> - type of entity in <code>entityPage</code>
* @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 <code>D</code>.
* @NB <code>dtoClass</code> must has NoArgsConstructor!
*/
public <D, T> Page<D> mapEntityPageIntoDtoPage(Page<T> entities, Class<D> dtoClass) {
return entities.map(objectEntity -> modelMapper.map(objectEntity, dtoClass));
}
This is exactly the case which you need (and I think common case for a wide range of other cases).
You already have the data obtained from repository (same is with service) on this way:
Page<ObjectEntity> entities = objectEntityRepository.findAll(pageable);
Everything what you need for conversion is to call this method on this way:
Page<ObjectDto> 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<ObjectDto> dtoPage = mapperUtil.mapEntityPageIntoDtoPage(entities, ObjectDto.class);
Page.map
without lambda expressions. Just pass an instance ofConverter<? super T, ? extends S>
– Maquette