jpa條件查詢與分頁條件查詢
阿新 • • 發佈:2021-09-28
首先JpaSpecificationExecutor這個介面的過載的findAll方法,Specification
查詢結果
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.creat_date as creat_da3_0_, user0_.name as name4_0_, user0_.pwd as pwd5_0_, user0_.title as title6_0_, user0_.update_date as update_d7_0_ from user user0_ where user0_.name=? and (user0_.age>10 or user0_.id<5) order by user0_.age asc, user0_.creat_date desc limit ? 2021-09-28 15:33:52.180 TRACE 7064 --- [nio-8080-exec-4] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [laowang]
程式碼:
@Override public Page<User> listPageAllUser(PageData<User> pageData) { //2、jpa 自帶的分頁查詢,可組裝條件的 Pageable pageable = PageRequest.of(pageData.getPageNumber()-1, pageData.getPageSize(), Sort.by("age").ascending().and(Sort.by("creatDate").descending())); /* * @param root:代表的查詢的實體類 * @param query:可以從中得到Root物件,即告知JPA Criteria查詢要查詢哪一個實體類, * 還可以來新增查詢條件,還可以結合EntityManager物件得到最終查詢的TypedQuery 物件 * @Param cb:criteriabuildre物件,用於建立Criteria相關的物件工程,當然可以從中獲取到predicate型別 * @return:代表一個查詢條件 */ Specification<User> specification = (Specification<User>) (root, query, criteriaBuilder) -> { Path age = root.get("age"); Path id = root.get("id"); Predicate p1 = criteriaBuilder.gt(age,pageData.getParams().getAge()); Predicate p2 = criteriaBuilder.lt(id,pageData.getParams().getId()); Predicate p3 = criteriaBuilder.equal(root.get("name").as(String.class), pageData.getParams().getName()); Predicate p = criteriaBuilder.and(p3,criteriaBuilder.or(p1,p2)); return p; }; Page<User> page = userDao.findAll(specification,pageable); return page; }
下面同事總結的圖