1.在Repository中定義相應的方法:
Page<EthicalApply> findByCreateTime(Date createTime, Pageable pageable);
Pageable pageable = PageRequest.of(page - 1,size);
2: 基於自定義的@Query
//在Repository中定義相應的JPL語句:
@Query("select e from apply e ORDER BY e.createTime ASC")
Page<ApplyEntity> findInApplys(Pageable pageable);
3: 基於Pageable中的Sort字段
Sort sort = new Sort(Direction.ASC, "createTime");
Pageable pageable = PageRequest.of(page-1, size, sort);
//在Repository無需聲明任何新的方法,直接使用JpaRepository中繼承而來的findAll(Pageable //pageable)方法即可。
//在Service中調用具體Repository中的方法如下
Page p = this.repo.findAll(pageable);
4: 條件分頁查詢
public Page<User> getUsersPage(PageParam pageParam, String nickName) {
//規格定義
Specification<User> specification = new Specification<User>() {
/**
* 構造斷言
* @param root 實體對象引用
* @param query 規則查詢對象
* @param cb 規則構建對象
* @return 斷言
*/
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<>(); //所有的斷言
if(StringUtils.isNotBlank(nickName)){ //添加斷言
Predicate likeNickName = cb.like(root.get("nickName").as(String.class),nickName+"%");
predicates.add(likeNickName);
}
return cb.and(predicates.toArray(new Predicate[0]));
}
};
//分頁信息 頁碼:前端從1開始,jpa從0開始,做個轉換
Pageable pageable = new PageRequest(page()-1,size);
//查詢
return this.userRepository.findAll(specification,pageable);
}