在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)进行降序排列的。