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

后端 未结 9 1640
太阳男子
太阳男子 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:16

    At the end, you will not return the Page to the users, but a list of ObjectDTO, with the Page details at the header, so this would be my solution.

    ObjectService

    public Page findAll (Pageable pageable){
      //logic goes here.
      Page page = objectRepository.findAll(pageable);
      return page;
    } 
    

    ObjectResource / rest (the exposed endpoint)

    @GetMapping
    public ResponseEntity> findAll (Pageable pageable){
      Page page = objectServiceService.findAll(pageable);
    
      HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "your-endpoint-here");
    
      return new ResponseEntity<>(objectMapper.toDto(page.getContent()), headers, HttpStatus.OK);
    }
    

    The reason for using this is so that you don't need to duplicate the page details for ObjectEntity and DTO. It is key to note that a page contains the following:

    • page number
    • pageSize
    • numberOfElements
    • content

    The content is the list of objects returned, and is the only thing that needs to be mapped to DTO.

提交回复
热议问题