我有一个主题实体,其中有很多帖子:
public class Topic extends TimeStampModel {
@Id
@Column
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String codeName;
@Column
private String description;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "topic")
private List<Post> posts;
public Topic(){}
//getters and setters omitted
}
打开主题页面时,我想检索所有帖子并将其显示给用户
我尝试使用分页实现此功能,但它返回的是所有帖子的字符串
控制器
@CrossOrigin
@GetMapping("/api/getpostsfor/{topicCodeName}")
public ResponseEntity<?> getPostsByTopicCodeName(@PathVariable String topicCodeName, Pageable pageable){
List<Post> posts = service.getPostsFor(topicCodeName);
if(posts == null){
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
//i am currentl trying to get only the first Post for testing
Page<Post> pages = new PageImpl<>(posts.subList(0, 1), pageable, posts.size());
return new ResponseEntity<>(pages, HttpStatus.OK);
}
服务
public List<Post> getPostsFor(String topicCodeName){
Topic topic = topicRepository.findFirstByCodeName(topicCodeName);
return topic == null ? null : topic.getPosts();
}
我正在检索该主题的所有帖子,因为最多将有100个主题,并且可能有数百万个帖子,所以我宁愿这样做而不是浏览所有帖子。
在春季这非常简单,您只需要将Pageable
类型的另一个参数传递给jpa方法:
public interface TopicRepository extends PagingAndSortingRepository<Topic, Long> {
List<Topic> findAllByCodeName(String codeName, Pageable pageable);
}
然后简单地调用方法:
findAllByCodeName(codeName, PageRequest.of(pageNum, pageSize))