Choose ... equivalent to JPA2 criteria

Is there a way to execute a query like the following using the JPA2 criteria APIs?

select a from b where a in (1, 2, 3, 4) 

There is a way to do this with simple Hibernate, but we cannot find anything like it in JPA2.

+4
source share
1 answer

Yes JPA 2 Critera supports returning a specific field from an object and using the where clause, which includes an in clause. I gave an example below that takes JPQL and converts it to a similar variant based on JPA 2 Criteria.

JPQL:

 select ba from B b where a in (1, 2, 3, 4) 

Criteria:

 CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); // assuming a is an Integer // if returning multiple fields, look into using a Tuple // or specifying the return type as an Object or Object[] CriteriaQuery<Integer.class> query = criteriaBuilder.createQuery(Integer.class); Root<B.class> from = query.from(Bean.class); query.select(from.get("a")) .where(from.get("a").in(1, 2, 3, 4)); // create query and execute... ... 

Here are a few links that give some additional examples of using in :

Hope this helps!

+7
source

All Articles