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','Raj') ORDER BY e.Parent
Let's see it step by step: Create an instance of Session from the SessionFactory object. Create an instance of CriteriaBuilder by calling the getCriteriaBuilder() method. Create an instance of CriteriaQuery by calling the CriteriaBuilder createQuery() method.
CriteriaBuilderJPA interfaceUsed to construct criteria queries, compound selections, expressions, predicates, orderings. See JavaDoc Reference Page... interface serves as the main factory of criteria queries and criteria query elements. It can be obtained either by the EntityManagerFactory. persistence.
CriteriaBuilder is the main interface into the Criteria API. A CriteriaBuilder is obtained from an EntityManager or an EntityManagerFactory using the getCriteriaBuilder() API. CriteriaBuilder is used to construct CriteriaQuery objects and their expressions. The Criteria API currently only supports select queries.
Interface CriteriaBuilder. Used to construct criteria queries, compound selections, expressions, predicates, orderings. Note that Predicate is used instead of Expression<Boolean> in this API in order to work around the fact that Java generics are not compatible with varags.
This criteria set-up should do the trick:
CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Employee> q = cb.createQuery(Employee.class); Root<Employee> root = q.from(Employee.class); q.select(root); List<String> parentList = Arrays.asList(new String[]{"John", "Raj"}); Expression<String> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With