在上篇文章 Spring Data MongoDB 環境搭建 基礎上進行分頁查詢 定義公用分頁參數類,實現 Pageable 介面
import java.io.Serializable;import org.springframework.data.domain.Pageable;import org.springframework.data.domain.Sort;public class SpringDataPageable implements Serializable, Pageable { private static final long serialVersionUID = 1; // 當前頁 private Integer pagenumber = 1; // 當前頁麵條數 private Integer pagesize = 10; // 排序條件 private Sort sort; // 當前頁面 @Override public int getPageNumber() { return getPagenumber(); } // 每一頁顯示的條數 @Override public int getPageSize() { return getPagesize(); } // 第二頁所需要增加的數量 @Override public int getOffset() { return (getPagenumber() - 1) * getPagesize(); } @Override public Sort getSort() { return sort; } public Integer getPagenumber() { return pagenumber; } public void setPagenumber(Integer pagenumber) { this.pagenumber = pagenumber; } public Integer getPagesize() { return pagesize; } public void setPagesize(Integer pagesize) { this.pagesize = pagesize; } public void setSort(Sort sort) { this.sort = sort; } @Override public Pageable first() { // TODO Auto-generated method stub return null; } @Override public boolean hasPrevious() { // TODO Auto-generated method stub return false; } @Override public Pageable next() { // TODO Auto-generated method stub return null; } @Override public Pageable previousOrFirst() { // TODO Auto-generated method stub return null; }}
介面 PersonDao
/** * 分頁查詢 * @param pageNum 開始頁 * @return */public Page<Person> paginationQuery(Integer pageNum);
介面實現 PersonDaoImpl
public Page<Person> paginationQuery(Integer pageNum) { SpringDataPageable pageable = new SpringDataPageable(); Query query = new Query(); List<Order> orders = new ArrayList<Order>(); //排序 orders.add(new Order(Direction.DESC, "age")); Sort sort = new Sort(orders); // 開始頁 pageable.setPagenumber(pageNum); // 每頁條數 pageable.setPagesize(10); // 排序 pageable.setSort(sort); // 查詢出一共的條數 Long count = mongoTemplate.count(query, Person.class); // 查詢 List<Person> list = mongoTemplate.find(query.with(pageable), Person.class); // 將集合與分頁結果封裝 Page<Person> pagelist = new PageImpl<Person>(list, pageable, count); return pagelist;}
測試
/** * 分頁查詢 */@Testpublic void paginationQuery(){ Page<Person> persons = personDao.paginationQuery(2); for(Person p : persons){ System.out.println(p.getName()); }}
作者:itmyhome