1.需求分析
简单的分页查询需要实现以上四个功能:①分页②左右翻页③自定义页面大小④跳转翻页
2.分页查询
①分页
public interface DepartDao extends JpaRepository<Depart,Long>,JpaSpecificationExecutor<Depart>{
}
//继承的JpaSpecificationExecutor接口具有分页功能
利用Specification类的对象来封装查询条件
//接口 匿名内部类 专门负责封装查询条件的
Specification specification= new Specification() {
// root 要查询实体类
// criteriaQuery 条件
// CriteriaBuilder 对象. 用于创建 Criteria 相关对象的工厂. 当然可以从中获取到
// Predicate 类型, 代表一个查询条件
@Override
public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
Predicate p1 = cb.notEqual(root.get("id"), 15); //条件1 id!=15
Predicate p2 = cb.like(root.get("email"), "%163.com"); // 条件2 email like '%163.com'
return cb.or(p1,p2);
}
};
PageRequest可以选择排序规则
Sort.Order order1=new Sort.Order(Sort.Direction.DESC, "id"); // 按id降序
Sort.Order order2=new Sort.Order(Sort.Direction.ASC, "age"); // 按age升序
Sort sort = new Sort(order1, order2); //Sort封装了排序规则
//分页条件对象
Pageable pageable = new PageRequest(pageIndex-1, pageSize,sort);
//specification查询条件封装的对象
//pageable分页条件
Page<Depart> page = userDao.findAll(specification,pageable);//带条件分页
//或取到当页数据集合
List<Depart> list = page.getContent();
Controller层,此处利用到了封装的分页工具类PageUtils
@RequestMapping("/list/{pageIndex}/{pageSize}")
public String getAllDepart(@PathVariable("pageIndex") int pageIndex,@PathVariable("pageSize")