Consider the following:
@Entity
public class Book
{
private List<String> authors;
@ElementCollection
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
}
How to type a JPA2 CriteriaQuery expression which, say, will let me find all the Books which have more than 2 authors?
This example shows how to use JPQL keyword MEMBER OF to determine whether a value is an element of a collection.
Queries can use IS EMPTY operator or IS NOT EMPTY to check whether a collection association path resolves to an empty collection or has at least one value. We can use the EMPTY to check if a property is empty. The following JPQL shows how to use EMPTY to get employee withno projects.
EntityManager instance is used to create a CriteriaBuilder object. CriteriaQuery instance is used to create a query object. This query object's attributes will be modified with the details of the query. CriteriaQuery. from method is called to set the query root.
In JPQL:
select b from Book where size(b.authors) >= 2
Using the criteria API (but why would you replace such a simple static query with the following mess?):
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Book> criteriaQuery = cb.createQuery(Book.class);
Root<Book> book = criteriaQuery.from(Book.class);
Predicate predicate = cb.ge(cb.size(book.get(Book_.authors)), 2);
criteriaQuery.where(predicate);
criteriaQuery.select(book);
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