Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top