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
ByLineareturnsnull, i get anullPointerExceptionfromcheckPackageAccesswhen resolving thewhereclause. - If
ByIngreturnsnull, it just gets ignored (like it should be) and the query matches just the other predicate. - If I switch the two predicates, putting
ByIngas the first one and thenByLineainside thewhereclause, everything works in every combination.