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

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

    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;
        }
    });
    
    0 讨论(0)
  • 2021-01-30 13:31

    Here is my solution, thanks to @Ali Dehghani

    private Page<ObjectDTO> mapEntityPageIntoDTOPage(Page<ObjectEntity> objectEntityPage) {
            return objectEntityPage.map(new Converter<ObjectEntity, ObjectDTO>() {
                public ObjectDTO convert(ObjectEntity objectEntity) {
                    return new ObjectDTO(objectEntity, httpSession);
                }
    
            });
        }
    
    0 讨论(0)
  • 2021-01-30 13:35

    This works correctly in Spring 2.0 -

    @Override
    public Page<BookDto> getBooksByAuthor(String authorId, Pageable pageable) {
            Page<BookEntity> bookEntity = iBookRepository.findByAuthorId(authorId, pageable);
            return bookEntity.map(new Function<BookEntity, BookDto>() {
    
                @Override
                public BookDto apply(BookEntity t) {
                    return new ModelMapper().map(t, BookDto.class);
                }
    
            });
        }
    

    The converter is no longer supported in Page type for Spring 2.0. Also, the Function should be used from java.util.function.Function.

    0 讨论(0)
提交回复
热议问题