8

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?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Sergey Beryozkin
  • 688
  • 1
  • 4
  • 9

1 Answers1

22

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);
tom_mai78101
  • 2,383
  • 2
  • 32
  • 59
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thank you, this is helpful; I'm working on mapping a URI query language to JPA2 expressions - CriteriaQuery API, while being verbose and arguably inflexible in some cases fits quite well for the purpose; JPQL is also initially supported - so extra thanks for another hint; btw - is select() actually needed or should "em.createQuery(criteriaQuery).getResultList()" follow instead ? – Sergey Beryozkin Dec 21 '12 at 09:48
  • 1
    I think I have been able to execute queries without select. But it was with Hibernate, whic dosen't need select in HQL queries either, whereas JPQL requires them. I would add a select clause, just to be sure. – JB Nizet Dec 21 '12 at 10:13
  • for "but why would you replace such a simple static query with the following mess?" – aroth Jun 26 '15 at 04:49