jpajpa-criteria

Criteria count + sub query


I am trying to implement something like:

Select thread from Thread where(Select Sum(thread.emails) from Thread) is equals to ?

How could I implement it with Criteria + JPA?


Solution

  • There is a size() method in CriteriaBuilder to define size of a collection.

    CriteriaBuilder cb = em.getCriteriaBuilder(); //em is EntityManager
    CriteriaQuery<Thread> cq = cb.createQuery(Thread.class);
    
    Root<Thread> root = cq.from(Thread.class);
    Expression<Collection<String>> emails = root.get("emails");
    cq.where(cb.equal(cb.size(emails), PARAM));