Search code examples
javahibernatejpacriteria-apijpa-criteria

JPA Criteria API "IN" Predicate not working


I need to write the following with JPA Criteria API:

p.id IS NULL  AND   nv.organizationalstat IN ('EMPLOYEE', 'FELLOW')`

My code is:

 List<String> corePredicateInList = Arrays.asList("EMPLOYEE", "FELLOW");
 In<String> corePredicateIn = cb.in(nvRoot.get("organizationalstat"));
 corePredicateInList.forEach(p -> corePredicateIn.value(p)); // Setting opts into IN
 Predicate p1CorePredicate = cb.and( 
                                cb.isNull(plans.get("id")), 
                                cb.in(nvRoot.get("organizationalstat"), corePredicateIn)
                            );

The runtime error is

antlr.NoViableAltException: unexpected token: in
...
where ( ( ( ( ( ( generatedAlias0.id is null ) 
  and ( generatedAlias1.organizationalstat in (:param0, :param1) in () ) ) 
  or ( generatedAlias0.id is not null ) )

It looks like there's a double IN somewhere. There are no syntax errors in the code.

I can't do cb.in(List<String>) directly, that's wrong syntax. I have to go through in.value() as indicated in this thread.


Solution

  • Using CriteriaBuilder.In

    Predicate p1CorePredicate = cb.and(cb.isNull(plans.get("id")),corePredicateIn);
    

    Or using Expression.In

    Predicate p1CorePredicate = cb.and(cb.isNull(plans.get("id")), 
                             nvRoot.get("organizationalstat").in(corePredicateInList));