Spring Data JPA 之分頁查詢
阿新 • • 發佈:2018-11-02
JPA的分頁查詢確實使用起來確實很簡單,但理解起來有點困難,此處只是實現JPA分頁的程式碼塊。
定義實體類:
@Entity @Table(name = "t_pub_info") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class InfoPO implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name ="name") private String name; @Column(name = "priority") private String priority; @Column(name = "pub_time") private Date pubTime; @Column(name = "depict") private String depict; @Column(name ="city_id") private Long cityId; @Column(name = "status") private String status; Getter... Setter... }
定義DAO:
public interface InfoDao extends JpaRepository<InfoPO, Long>, JpaSpecificationExecutor<InfoPO> {
}
定義介面:
@SuppressWarnings(value = "unused") @RestController @RequestMapping(value = "/info") public class InfoController { @Autowired InfoService infoService; @GetMapping(value = "/list") Object queryInfoList(@RequestParam(value = "pageNo", required = false, defaultValue = "0") Integer pageNo, @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "priority", required = false) String priority, @RequestHeader("city_id")Integer cityId) { return infoService.queryInfoList(pageNo, pageSize, priority,cityId,String status); } }
定義service
public interface InfoService {
Object queryinfoList(Integer pageNo, Integer pageSize, String priority,Integer cityId,String status);
}
實現service
@Service public class InfoServiceImpl implements InfoService { protected static final int PAGE_SIZE = 5; @Autowired InfoDao infoDao; public Object queryInfoList(Integer pageNo, Integer pageSize, String priority,Integer cityId,String status) { //驗證city_id if(cityId == null){ throw new Exception("city id necessary"); } Integer currentPage = pageNo == null ? 0 : pageNo; Page<InfoPO> page = infoDao.findAll((Root<InfoPO> root, CriteriaQuery<?> cq, CriteriaBuilder cb) -> { //新增分頁篩選條件 List<Predicate> predicates = new ArrayList<>(); if (priority != null) { predicates.add(cb.equal(root.get("priority"), priority)); } if (status != null) { String statusName = status; if (StringUtils.isNotBlank(statusName)) { predicates.add(cb.equal(root.get("status"), statusName)); } } if (cityId != null) { predicates.add(cb.equal(root.get("cityId"), cityId)); } return cb.and(predicates.toArray(new Predicate[]{})); }, new PageRequest(currentPage, pageSize, new Sort(Sort.Direction.DESC, "pubTime"))); //獲取頁面資料以及分頁資料 List<InfoPO> infos = page.getContent(); Integer totalPage = page.getTotalPages(); Long totalElement = page.getTotalElements(); return infos; } }