How to map Page to Page in spring-data-rest

后端 未结 9 1641
太阳男子
太阳男子 2021-01-30 12:37

When I hit the database with PagingAndSortingRepository.findAll(Pageable) I get Page. However, I want to expose DTO\'s to the clien

9条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 13:24

    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);
    

提交回复
热议问题