我想用Spring Data Mongo实现分页.有许多教程和文档建议使用PagingAndSortingRepository,如下所示:
StoryRepo extends PagingAndSortingRepository{}
因此,因为PagingAndSortingRepository为分页查询提供api,我可以使用它:
Pagestory = storyRepo.findAll(pageable);
我的问题是这里的findAll方法实际上是在哪里实现的?我需要自己编写实现吗?实现StoryRepo的StoryRepoImpl需要实现这个方法吗?
您不需要像自动装配Spring对象PagingAndSortingRepository那样实现该方法,它会自动为您实现该方法.
请注意,由于您使用的是Mongodb,因此您可以扩展MongoRepository.
然后在Spring中,使用以下命令启用分页:
@RequestMapping(value="INSERT YOUR LINK", method=RequestMethod.GET) public List<Profile> getAll(int page) { Pageable pageable = new PageRequest(page, 5); //get 5 profiles on a page Page<Profile> page = repo.findAll(pageable); return Lists.newArrayList(page);
我通过编写自己的实现来实现它,如下所示:
List<Story> stories = null; Query query = new Query(); query.with(pageable); stories = getTemplate().find(query, Story.class); long total = getTemplate().count(query, Story.class); Page<Story> storyPage = new PageImpl<Story>(stories, pageable, total); return storyPage;
我正在使用spring data&mongodb,使用mongo模板查询数据.