How to check a collection size in JPA2

2019-02-13 17:18发布

问题:

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?

回答1:

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 = criteria.from(Book.class);
Predicate predicate = cb.ge(cb.size(book.get(Book_.authors)), 2);
criteriaQuery.where(predicate);
criteriaQuery.select(