I wrote two Specifications which return null if their parameter is null.
public static Specification<Prodotto> getProdottoByLineaSpec (String linea) {
if (linea != null) {
return (root, query, criteriaBuilder) -> {
return criteriaBuilder.like((root.join("linea")).get("nome"), "%"+linea+"%");
};
}
else return null;
}
public static Specification<Prodotto> getProdottoByIngSpec (String ing) {
if (ing != null) {
return (root, query, criteriaBuilder) -> {
return criteriaBuilder.like(((root.join("listaQuoteIng")).join("ing")).get("nome"), "%"+ing+"%");
};
}
else return null;
}
Then I created a third one that combines the previous ones with an and
operator inside a where
clause:
public static Specification<Prodotto> getProdottoByMainTraits (String linea, String ing) {
return Specification.where(getProdottoByLineaSpec(linea).and(getProdottoByIngSpec(ing)));
}
Now, that's the funny part:
- If
ByLinea
returnsnull
, i get anullPointerException
fromcheckPackageAccess
when resolving thewhere
clause. - If
ByIng
returnsnull
, it just gets ignored (like it should be) and the query matches just the other predicate. - If I switch the two predicates, putting
ByIng
as the first one and thenByLinea
inside thewhere
clause, everything works in every combination.
else return (root, query, criteriaBuilder) -> criteriaBuilder.conjunction();
I upvote your answer, but wait to mark it as solution, because it doesn't explain why my original structure got no problem if I switch predicates order inside where clause. – Yalu