How to check a collection size in JPA2

2019-02-13 17:30发布

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条回答
ら.Afraid
2楼-- · 2019-02-13 17:44

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(
查看更多
登录 后发表回答