0%

jpa动态查询条件

1
2
3
4
5
6
7
8
@Data
@AllArgsConstructor
public class SearchCriteria {
private String key;
private Object value;
private SearchOperation operation;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public enum SearchOperation {

GREATER_THAN,
LESS_THAN,
GREATER_THAN_EQUAL,
LESS_THAN_EQUAL,
NOT_EQUAL,
EQUAL,
LIKE,
LIKE_START,
LIKE_END,
IN,
NOT_IN
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

public class Specification<T> implements Specification<T> {
private List<SearchCriteria> list = new ArrayList<>();

public void add(SearchCriteria criteria) {
list.add(criteria);
}


@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
List<Predicate> predicates = new ArrayList<>();
for (SearchCriteria criteria : list) {
switch (criteria.getOperation()) {
case GREATER_THAN:
predicates.add(builder.greaterThan(root.get(criteria.getKey()), criteria.getValue().toString()));
break;
case LESS_THAN:
predicates.add(builder.lessThan(root.get(criteria.getKey()), criteria.getValue().toString()));
break;
case GREATER_THAN_EQUAL:
predicates.add(builder.greaterThanOrEqualTo(root.get(criteria.getKey()), criteria.getValue().toString()));
break;
case LESS_THAN_EQUAL:
predicates.add(builder.lessThanOrEqualTo(root.get(criteria.getKey()), criteria.getValue().toString()));
break;
case NOT_EQUAL:
predicates.add(builder.notEqual(root.get(criteria.getKey()), criteria.getValue()));
break;
case EQUAL:
predicates.add(builder.equal(root.get(criteria.getKey()), criteria.getValue()));
break;
case LIKE:
predicates.add(builder.like(builder.lower(root.get(criteria.getKey())), "%" + criteria.getValue().toString().toLowerCase() + "%"));
break;
case LIKE_END:
predicates.add(builder.like(builder.lower(root.get(criteria.getKey())), criteria.getValue().toString().toLowerCase() + "%"));
break;
case LIKE_START:
predicates.add(builder.like(builder.lower(root.get(criteria.getKey())), "%" + criteria.getValue().toString().toLowerCase()));
break;
case IN:
predicates.add(builder.in(root.get(criteria.getKey())).value(criteria.getValue()));
break;
case NOT_IN:
predicates.add(builder.not(root.get(criteria.getKey())).in(criteria.getValue()));
break;
}
}
return builder.and(predicates.toArray(new Predicate[0]));
}
}

1
2
3
4
5
6
7
8
9
10
11
12
@PostMapping
ResponseEntity specification(@RequestBody List<SearchCriteria> searchCriteria) {
UserSpecification<UserEntity> appleSpecification = new UserSpecification();
searchCriteria.stream().map(
searchCriterion -> new SearchCriteria(searchCriterion.getKey(),
searchCriterion.getValue(),
searchCriterion.getOperation())).forEach(appleSpecification::add);
List<UserEntity> msGenreList = userDao.findAll(appleSpecification);
msGenreList.forEach(System.out::println);

return ResponseEntity.status(HttpStatus.OK).body(msGenreList);
}