q.select(book);
// Builds the predicates conditionally for the filled-in input fields
List<Predicate> predicates = new ArrayList<Predicate>();
if (!isEmpty(title)) {
Predicate matchTitle = cb.like(book.get(Book_.title), title);
predicates.add(matchTitle);
}
if (!isEmpty(author)) {
Predicate matchAuthor = cb.like(book.join(Book_.authors).get(Author_.name), "%"+author+"%");
predicates.add(matchAuthor);
}
// for price fields, also the comparison operation changes based on whether
// minimum or maximum price or both have been filled.
if (minPrice != null && maxPrice != null) {
Predicate matchPrice = cb.between(book.get(Book_.price), minPrice, maxPrice);
predicates.add(matchPrice);
} else if (minPrice != null && maxPrice == null) {
Predicate matchPrice = cb.ge(book.get(Book_.price), minPrice);
predicates.add(matchPrice);
} else if (minPrice == null && maxPrice != null) {
Predicate matchPrice = cb.le(book.get(Book_.price), maxPrice);
predicates.add(matchPrice);
}
// Sets the evaluation criteria
if (!predicates.isEmpty())
q.where(predicates.toArray(new Predicate[predicates.size()]));