Select ... in equivalent in JPA2 criteria

12,872

Yes JPA 2 Critera supports returning a specific field from a entity and using a where clause which includes an in clause. I have included an example below which takes a JPQL and converts it to a similar JPA 2 Criteria-based option.

JPQL:

select b.a 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 some links that give some addition examples of using in:

Hope this helps!

Share:
12,872

Related videos on Youtube

user2756501
Author by

user2756501

Master geek, developer, avid reader and one of the minds behind novlet.com and bitlet.org :P@abahgat

Updated on May 29, 2022

Comments

  • user2756501
    user2756501 almost 2 years

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

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

    There's a way to do that using plain Hibernate, but we can't find anything like that in JPA2.