26

Is there a possibility to use a parameter list in Criteria API .in expression?

I have something like this:

    List<Long> list = new ArrayList<Long>();
    list.add((long)1);
    list.add((long)2);
    list.add((long)3);


CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Bewerbung> criteriaQuery = cb.createQuery(Bewerbung.class);
Root<Bewerbung> bewerbung = criteriaQuery.from(Bewerbung.class);

criteriaQuery.select(bewerbung).where(
cb.in(bewerbung.get(Bewerbung_.bewerberNummer)).value(list);

return em.createQuery(criteriaQuery).getResultList();

The expression .value(list) does not work as value() is expecting a paramter of type long not a list. In my case it is not possible to use a subquery. Can anyone help me on this issue?

user1414341
  • 321
  • 1
  • 4
  • 6

2 Answers2

37

No need to use CriteriaBuilder#isTrue. This should suffice:

criteriaQuery.select(bewerbung)
             .where(bewerbung.get(Bewerbung_.bewerberNummer)
             .in(list));
jFrenetic
  • 5,384
  • 5
  • 42
  • 67
  • Instead of "no need" I would say "must not". At least using EclipseLink 2.6.2 for sure. I have tested. – Miklos Krivan May 09 '16 at 16:01
  • @MiklosKrivan well, both should work, this just looks clearer to me. – jFrenetic May 09 '16 at 20:13
  • I would expect so as well but unfortunately using EclipseLink 2.6.2 for ORM (I have tried both formula) the isTrue() wrapping raises the mentioned exception. That is why my wording suggestion given. So theoretically "no need" but practically "must not". – Miklos Krivan May 10 '16 at 09:02
  • @MiklosKrivan will have to check, thanks for clarifying. – jFrenetic May 10 '16 at 14:21
  • @MiklosKrivan can you, please, share your stack trace on `pastebin` or someplace else, if possible? – jFrenetic May 10 '16 at 15:00
34
cb.isTrue(bewerbung.get(Bewerbung_.bewerberNummer).in(list));

should do the trick, AFAIK.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Great, thanks this works, but I'm using Hibernate and it seems that Hibernate doesn't support empty collection as parameter of javax.persistence.criteria.Expression "in" method parameter. See http://lists.jboss.org/pipermail/hibernate-issues/2011-December/035927.html – user1414341 May 24 '12 at 09:21
  • AFAIK, no-one supports them. You should probably short-circuit the query in case an empty list is passed as argument. – JB Nizet May 24 '12 at 09:30
  • I have found this expression (wrapped in isTrue) raises exception PREDICATE_PASSED_TO_EVALUATION in EclipseLink 2.6.2 but without isTrue wrapping works perfect as predicate in my example probably because "in" returns with Predicate object. – Miklos Krivan May 09 '16 at 13:04