Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a collection size in JPA2

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?

like image 761
Sergey Beryozkin Avatar asked Dec 20 '12 21:12

Sergey Beryozkin


People also ask

Which JPQL keyword is used to determine whether a value is an element of a collection in JPA?

This example shows how to use JPQL keyword MEMBER OF to determine whether a value is an element of a collection.

Is empty in JPQL?

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.

What is CriteriaBuilder in JPA?

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.


1 Answers

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);
like image 158
JB Nizet Avatar answered Sep 22 '22 16:09

JB Nizet