JPA Criteria builder IN clause query

前端 未结 5 1744
花落未央
花落未央 2020-11-30 07:20

How to write criteria builder api query for below given JPQL query? I am using JPA 2.2.

SELECT * 
FROM Employee e
WHERE e.Parent IN (\'John\',\'         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 07:57

    This criteria set-up should do the trick:

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery q = cb.createQuery(Employee.class);
    
    
    Root root = q.from(Employee.class);
    q.select(root);
    
    List parentList = Arrays.asList(new String[]{"John", "Raj"});
    
    Expression parentExpression = root.get(Employee_.Parent);
    Predicate parentPredicate = parentExpression.in(parentList);
    q.where(parentPredicate);
    q.orderBy(cb.asc(root.get(Employee_.Parent));
    
    q.getResultList();
    

    I have used the overloaded CriteriaQuery.where method here which accepts a Predicate.. an in predicate in this case.

提交回复
热议问题