2011-04-18 106 views
4

有沒有什麼方法可以使用JPA2標準API執行類似下面的查詢?在JPA2標準中選擇......等效於

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

有一種使用普通Hibernate的方法,但我們在JPA2中找不到類似的東西。

回答

7

是JPA 2 Critera支持從實體返回特定字段,並使用where子句包含in子句。我在下面的例子中包含了一個JPQL並將其轉換爲類似的基於JPA 2標準的選項。

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的一些另外的例子:

希望這有助於!