How to map Page<ObjectEntity> to Page<ObjectDTO> in spring-data-rest

Tuomas Toivonen picture Tuomas Toivonen · Aug 19, 2016 · Viewed 30.8k times · Source

When I hit the database with PagingAndSortingRepository.findAll(Pageable) I get Page<ObjectEntity>. However, I want to expose DTO's to the client and not entities. I can create DTO just by injecting entity into it's constructor, but how do I map the entities in Page object to DTO's? According to spring documentation, Page provides read-only operations.

Also, Page.map is not possibility, as we don't have support for java 8. How to create the new Page with mapped objects manually?

Answer

Ali Dehghani picture Ali Dehghani · Aug 19, 2016

You can still use the Page.map without lambda expressions:

Page<ObjectEntity> entities = objectEntityRepository.findAll(pageable);
Page<ObjectDto> dtoPage = entities.map(new Converter<ObjectEntity, ObjectDto>() {
    @Override
    public ObjectDto convert(ObjectEntity entity) {
        ObjectDto dto = new ObjectDto();
        // Conversion logic

        return dto;
    }
});