• Java中分页查询MongoDB数据


      在Java中操作MongoDB时会遇到分页查询数据的情况,此时我们可以按如下步骤来实现:

      1、创建一个分页类

    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.domain.Sort;
    
    public class MongoDbPageable implements Pageable {
        /**分页码*/
        private int pageNumber = 1;
        /**每页大小*/
        private int pageSize = 10;
        /**排序*/
        private Sort sort;
    
        @Override
        public int getPageNumber() {
            return pageNumber;
        }
    
        public void setCurrentPage(int pageNumber) {
            this.pageNumber = pageNumber;
        }
    
        @Override
        public int getPageSize() {
            return pageSize;
        }
    
        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }
    
        @Override
        public Sort getSort() {
            return sort;
        }
    
        public void setSort(Sort sort) {
            this.sort = sort;
        }
    
        @Override
        public long getOffset() {
            return (pageNumber - 1) * pageSize;
        }
    
        @Override
        public Pageable first() {
            return PageRequest.of(0, pageSize, sort);
        }
    
        @Override
        public boolean hasPrevious() {
            return false;
        }
    
        @Override
        public Pageable next() {
            return PageRequest.of(pageNumber + 1, pageSize, sort);
        }
    
        @Override
        public Pageable previousOrFirst() {
            return pageNumber == 0 ? this : PageRequest.of(pageNumber - 1, pageSize, sort);
        }
    }

      2、分页类的实践

    private List<Object> find(int pageNumber, int pageSize,  Sort.Direction direction){
             MongoDbPageable pageable = new MongoDbPageable();
             pageable.setCurrentPage(pageNumber);
             pageable.setPageSize(pageSize);
             // direction: Sort.Direction.DESC或者Sort.Direction.ASC
             Sort sort = new Sort(direction, "_id");
             pageable.setSort(sort);
             Query query = new Query();
             query.with(pageable);
             return mongoTemplate.find(query, Object.class, collectionName);
         }

      说明:分页类具有排序的功能,实践中是按照ObjectId(_id)进行降序排列的。

  • 相关阅读:
    LeetCode——二叉树中的最大路径和
    LeetCode——验证回文串
    LeetCode——word-ladder*
    LeetCode——最长连续序列
    3G? 2G? 2.5G? 4G? 与 WIFI, GPRS,CDMA 3G无线上网
    GSM、GPRS、EDGE、2G、3G与WAP的关系
    3G 2G GPRS 1G的概念
    那些精华博客
    单片机系统与标准PC键盘的接口模块设计
    以多个实例方式打开Notepad++
  • 原文地址:https://www.cnblogs.com/bien94/p/13187292.html
Copyright © 2020-2023  润新知