事情有点多,于是快一个月没写东西了,今天补上上次说的。
1 /**
2 * 获取Sort
3 *
4 * @param direction - 排序方向
5 * @param column - 用于排序的字段
6 */
7 public static Sort getSort(String direction,String column){
8 Sort sort = null;
9 if(column == null || column == "") return null;
10 if(direction.equals("asc")||direction.equals("ASC")){
11 sort = Sort.by(Sort.Direction.ASC,column);
12 }else {
13 sort = Sort.by(Sort.Direction.DESC,column);
14 }
15 return sort;
16 }
17 /**
18 * 获取分页
19 * @param pageNumber 当前页
20 * @param pageSize 页面大小
21 * @param sort 排序;sort为空则不排序只分页
22 * @return 分页对象
23 */
24 public static Pageable getPageable(int pageNumber,int pageSize,Sort sort){
25 if(sort!=null){
26 return PageRequest.of(pageNumber,pageSize,sort);
27 }
28 return PageRequest.of(pageNumber,pageSize);
29 }
30 /**
31 * 判断String是否为空
32 * @param str
33 * @return
34 */
35 private static boolean isEmpty(String str){
36 if(str.equals(null)||str.equals("")) return true;
37 return false;
38 }
2、实现类
这里查询相关参数是前端传的,我懒,所以用默认值了,查询条件可以是多条件动态,排序也可以是动态的,只要传排序字段和排序方向对号入座即可。
1 @Override
2 public Page<User> findAll() {
3 // 创建测试对象
4 User user = new User();
5 user.setName("1");
6 Sort sort = Utils.getSort("asc","name");
7 Pageable pageable = Utils.getPageable(0,5,sort);
8 // 调用组装查询条件方法
9 Specification<User> spec = getSpecification(user);
10 return userRepository.findAll(spec,pageable);
11 }
12
13 /**
14 * 组装查询条件
15 * @param user -查询相关对象
16 * @return 返回组装过的多查询条件
17 */
18 private Specification<User> getSpecification(User user) {
19 Specification<User> specification = new Specification<User>() {
20 @Override
21 public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
22 List<Predicate> predicates = new ArrayList<>();
23 // 判断条件不为空
24 if(!Utils.isEmpty(user.getName())){
25 predicates.add(criteriaBuilder.like(root.get("name"),user.getName()));
26 }
27 return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
28 }
29 };
30 return specification;
31 }
3.repository类中需要这么干
1 @Repository
2 public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {}
原文:https://www.cnblogs.com/hellohmbb/p/13545406.html