Spring数据mongo分页

 手机用户敬怡 发布于 2023-02-13 07:27

我想用Spring Data Mongo实现分页.有许多教程和文档建议使用PagingAndSortingRepository,如下所示:

StoryRepo extends PagingAndSortingRepository{}

因此,因为PagingAndSortingRepository为分页查询提供api,我可以使用它:

Page story = storyRepo.findAll(pageable);

我的问题是这里的findAll方法实际上是在哪里实现的?我需要自己编写实现吗?实现StoryRepo的StoryRepoImpl需要实现这个方法吗?

2 个回答
  • 您不需要像自动装配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);
    

    2023-02-13 07:44 回答
  • 我通过编写自己的实现来实现它,如下所示:

    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模板查询数据.

    2023-02-13 07:45 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有