Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 879
Tuomas Toivonen Avatar asked Aug 19 '16 10:08

Tuomas Toivonen


People also ask

What is the difference between DTO and entity?

An Entity is defined only for the purpose of storing it in a database. It is, simply, a Java representation of a table in a database. A DTO, on the other hand, is the class we use for all operations other than database-related ones.


2 Answers

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;     } }); 
like image 59
Ali Dehghani Avatar answered Sep 27 '22 20:09

Ali Dehghani


In Spring Data 2, the Page map method takes a Function instead of a Converter, but it still works basically the same as @Ali Dehghani described.

Using Function:

Page<ObjectEntity> entities = objectEntityRepository.findAll(pageable); Page<ObjectDto> dtoPage = entities.map(new Function<ObjectEntity, ObjectDto>() {     @Override     public ObjectDto apply(ObjectEntity entity) {         ObjectDto dto = new ObjectDto();         // Conversion logic          return dto;     } }); 
like image 36
JayL Avatar answered Sep 27 '22 20:09

JayL