Select … in equivalent in JPA2 criteria

情到浓时终转凉″ 提交于 2019-12-22 08:12:13

问题


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.


回答1:


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:

  • Pro JPA 2: mastering the Java Persistence API
  • eAltuure Blog

Hope this helps!



来源:https://stackoverflow.com/questions/5705291/select-in-equivalent-in-jpa2-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!