Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Criteria builder IN clause query

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 
like image 559
Raj Avatar asked Mar 01 '17 11:03

Raj


People also ask

How do I create a query in criteria builder?

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.

What is CriteriaBuilder in JPA?

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.

What is a CriteriaBuilder?

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.

Why we use criteria builder in Java?

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.


1 Answers

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.

like image 129
Maciej Kowalski Avatar answered Oct 02 '22 17:10

Maciej Kowalski