0

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?

Laurel
  • 5,965
  • 14
  • 31
  • 57
Blanca Hdez
  • 3,513
  • 19
  • 71
  • 93

1 Answers1

1

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));
d1e
  • 6,372
  • 2
  • 28
  • 41
  • How, great, thanks! I am a completely newbie in Criteria... I couldn´t find something similar to get the first/las element from an array. Get TOP 1 in order by, but maybe there are some easy way like the one you suggested me for the size? Thanks – Blanca Hdez Jun 29 '12 at 13:16
  • @BlancaHdez do you lazy initialize collection on which you are calling TOP 1? – d1e Jun 29 '12 at 13:21
  • Not lazy but eager --> FetchType.EAGER – Blanca Hdez Jun 29 '12 at 13:23
  • @BlancaHdez I suggest you using FetchType.LAZY, depending on size of collections of course. Well, there are [Hibernate's LazyCollectionOption.EXTRA](https://sites.google.com/a/pintailconsultingllc.com/java/hibernate-extra-lazy-collection-fetching) to call get() method on collection, which will query database on specific element, without retrieving all the collection. To achieve first element, you can [set number of results](http://www.objectdb.com/java/jpa/query/setting) retrieved from db. Of course, it is if you use LAZY, not EAGER. Also, read [JPA Manual](http://www.objectdb.com/java/jpa). – d1e Jun 29 '12 at 13:28