JpaSpecificationExecutor(Jpa规则执行者)
@Test
public void testSpec02(){
// 创建排序对象
Sort sort = new Sort(Sort.Direction.DESC, "age");
// 创建分页对象
Pageable pageable = new PageRequest(1, 10, sort);
Page<Employee> page = employeeRepository.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
// 获取字段
Path username = root.get("username");
Path age = root.get("age");
// 为字段添加条件
Predicate p1 = criteriaBuilder.like(username, "%1%");
Predicate p2 = criteriaBuilder.gt(age, 22);
// 整合条件
Predicate p = criteriaBuilder.and(p1, p2);
return p;
}
}, pageable);
page.forEach(employee -> System.out.println(employee));
}
}, pageable);
page.forEach(employee -> System.out.println(employee));
}