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])); } }
|