为什么在春季启动中没有收到可分页的详细信息?



我正在一个 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);
}

将返回类型调整为Page<PostOutputDTO>而不是List<PostOutputDTO>

List<PostOutputDTO>转换为Page<PostOutputDTO>的最简单方法是

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

更新:

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

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

所以问题来自返回ListPostAssembler#toResources,我们错误地将其转换为Page

如果我没看错,您正在利用ResourceAssemblerSupportIterable<Post>(更准确地说,Page<Post>(映射到List<PostOutputDTO>

我的建议是不要使用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;
}

有关详细信息,请参阅参考

最新更新