首先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;
}
下面同事总结的图