JPA Criteria API IN expression Parameter list
Asked Answered
D

2

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?

Dependence answered 24/5, 2012 at 7:25 Comment(0)
F
37

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

criteriaQuery.select(bewerbung)
             .where(bewerbung.get(Bewerbung_.bewerberNummer)
             .in(list));
Frodina answered 30/10, 2012 at 18:23 Comment(5)
Instead of "no need" I would say "must not". At least using EclipseLink 2.6.2 for sure. I have tested.Crackle
@MiklosKrivan well, both should work, this just looks clearer to me.Frodina
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".Crackle
@MiklosKrivan will have to check, thanks for clarifying.Frodina
@MiklosKrivan can you, please, share your stack trace on pastebin or someplace else, if possible?Frodina
R
34
cb.isTrue(bewerbung.get(Bewerbung_.bewerberNummer).in(list));

should do the trick, AFAIK.

Rosalindrosalinda answered 24/5, 2012 at 7:56 Comment(3)
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 lists.jboss.org/pipermail/hibernate-issues/2011-December/…Dependence
AFAIK, no-one supports them. You should probably short-circuit the query in case an empty list is passed as argument.Rosalindrosalinda
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.Crackle

© 2022 - 2024 — McMap. All rights reserved.