提问者:小点点

为什么不在Spring启动中接收可分页的详细信息?


我在一个Spring启动项目中工作。我需要返回一个带有分页的列表。目前我可以在参数中选择页面和大小,但我没有收到页面详细信息,例如:

"last": false,
"totalElements": 20,
"totalPages": 7,
"size": 3,
"number": 0,
"sort": null,
"first": true,
"numberOfElements": 3

我只是收到一个没有它的正常响应。我想我需要将方法响应类型更改为响应实体或资源。有什么想法吗?

控制器:

public List<PostOutputDTO> getTopicPosts(@PathVariable("id") UUID topicId, Pageable pageable) {
   return postService.getActivePosts(topicId, pageable);

服务:

 public List<PostOutputDTO> getActivePosts(UUID topicId, Pageable pageable) throws AccessDeniedException {
    Topic topic = topicRepo.findByIdAndDeactivatedAtIsNull(topicId).orElseThrow(() -> new EntityNotFoundException("This topic doesn't exist."));
    if (topic.getType() != TopicType.GLOBAL) {
        throw new AccessDeniedException("This is not a global topic.");
    }
    return postAssembler.toResources(postRepo.findPostsByTopicAndDeactivatedAtIsNull(topic, pageable));
}

汇编器:

@Service
public class PostAssembler extends ResourceAssemblerSupport<Post, PostOutputDTO> {

    @Autowired
    private ForumUserAssembler forumUserAssembler;

    @Autowired
    private TopicAssembler topicAssembler;

    @Autowired
    private ContentRepo contentRepo;

    public PostAssembler() {
        super(PostController.class, PostOutputDTO.class);
    }

    public PostOutputDTO toResource(Post post) {
        return PostOutputDTO.builder()
                .uuid(post.getId())
                .topic(topicAssembler.toResource(post.getTopic()))
                .text(contentRepo.findByPostAndDeactivatedAtIsNull(post).orElseThrow(() -> new EntityNotFoundException("This post doesn’t have content")).getText())
                .createdAt(post.getCreatedAt())
                .createdBy(forumUserAssembler.toResource(post.getCreatedBy()))
                .build();
    }
}

存储库:

@Repository
public interface TopicRepo extends JpaRepository<Topic, UUID> {

    Page<Topic> findAllByTypeAndDeactivatedAtIsNull(TopicType topicType, Pageable pageable);

}

共2个答案

匿名用户

调整返回类型为Page

转换列表的最简单方法

public Page<PostOutputDTO> getTopicPosts(@PathVariable("id") UUID topicId, Pageable pageable) {
    return new PageImpl<>(postService.getActivePosts(topicId, pageable));
}

更新:

我仍然没有看到全貌,但我希望存储库方法返回Page实例,

Page<Post> findPostsByTopicAndDeactivatedAtIsNull(...);
Page<Topic> findAllByTypeAndDeactivatedAtIsNull(...);

所以问题来自PostAssembler#toResources它返回一个List,我们不准确地将其转换为Page返回。

如果我没弄错的话,您正在使用ResourceAssemblerSupport来映射Iterable

我的建议是不要使用PostAssembler#toResources并坚持使用PostAssembler#toResourcePage#map

postRepo.findPostsByTopicAndDeactivatedAtIsNull(topic, pageable)
        .map(postAssembler::toResource);

匿名用户

您必须从Spring返回接口页面:

页面是对象列表的子列表。它允许获取有关它在包含中的位置的信息。

参见示例:

public Page<PostOutputDTO>  getActivePosts(UUID topicId, Pageable pageable) {

    Page<PostOutputDTO>  list=postService.getActivePosts(topicId, pageable);

      return  list;

}

有关更多信息,请参阅参考