选择...在JPA2标准中等效 [英] Select ... in equivalent in JPA2 criteria

查看:82
本文介绍了选择...在JPA2标准中等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以使用JPA2标准API来执行以下查询?

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)

有一种方法可以使用普通的Hibernate来实现,但是我们在JPA2中找不到类似的东西.

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

推荐答案

是的,JPA 2 Critera支持从实体返回特定字段,并支持使用包含in子句的where子句.我在下面提供了一个使用JPQL并将其转换为类似的基于JPA 2 Criteria的选项的示例.

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)

条件:

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...
...  

以下是一些链接,这些链接提供了使用in的其他示例:

Here are some links that give some addition examples of using in:

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

希望这会有所帮助!

这篇关于选择...在JPA2标准中等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆