Here the IN criteria query using Spring JPA Specification is working fine. but I don't know how to use "NOT IN"..
So How can i use the NOT IN criteria query using Spring JPA Specifications.
SearchSpecification<User> spec = new CommonSpecification<Case>(new SearchCriteria("client.id", Operator.NOT_IN, clientIdList));
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Predicate predicate = null;
switch (searchCriteria.getOperator()) {
case IN:
if (searchCriteria.getValue() instanceof List<?>) {
predicate = getFieldPath(searchCriteria.getKey(), root)
.in(((List<?>) searchCriteria.getValue()).toArray());
}
break;
case NOT_IN:
//What to do???
break;
default:
break;
}
return predicate;
}
private Path<Object> getFieldPath(String key, Root<T> root) {
Path<Object> fieldPath = null;
if (key.contains(".")) {
String[] fields = key.split("\\.");
for (String field : fields) {
if (fieldPath == null) {
fieldPath = root.get(field);
} else {
fieldPath = fieldPath.get(field);
}
}
} else {
fieldPath = root.get(key);
}
return fieldPath;
}
SPring Data Jpa Specifications helps us to create dynamic queries based on the requirement at run time. Spring Data Jpa Specifications allows a combination of the attributes or properties of a domain or entity class and creates a query.
Spring Data JPA is not an implementation or JPA provider, it's just an abstraction used to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.
The JpaSpecificationExecutor interface adds methods which will allow us to execute Specification s, for example, these: List<T> findAll(Specification<T> spec); Page<T> findAll(Specification<T> spec, Pageable pageable); List<T> findAll(Specification<T> spec, Sort sort);
Use the Predicate.not()
method; the code is the same as in the IN
case, just add .not()
:
case NOT_IN:
if (searchCriteria.getValue() instanceof List<?>) {
predicate = getFieldPath(searchCriteria.getKey(), root)
.in(((List<?>) searchCriteria.getValue()).toArray())
.not();
}
break;
This functionality also works fine..
case NOT_IN:
if (searchCriteria.getValue() instanceof List<?>) {
predicate = criteriaBuilder.not(getFieldPath(searchCriteria.getKey(), root).in(((List<?>) searchCriteria.getValue()).toArray()));
}
break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With