2012-09-14 86 views
10

我試圖寫一個不同的條件查詢,使用:JPA條件查詢不同

CriteriaBuilder builder = em.getCriteriaBuilder(); 
CriteriaQuery<RuleVar> query = builder.createQuery(RuleVar.class); 
Root<RuleVar> ruleVariableRoot = query.from(RuleVar.class); 
query.select(ruleVariableRoot.get("foo").<String>get("foo")).distinct(true); 

基於在Javadoc的例子爲CriteriaQuery.select()

CriteriaQuery<String> q = cb.createQuery(String.class); 
Root<Order> order = q.from(Order.class); 
q.select(order.get("shippingAddress").<String>get("state")); 

然而,這給我錯了:

The method select(Selection<? extends RuleVar>) in the type CriteriaQuery<RuleVar> is not applicable for the arguments (Path<String>) 

有人可以指出我做錯了什麼嗎?或者如何從Path中獲取Selection對象?

回答

38

我明白了。問題是我的CriteraQuery需要是String類型的。此作品:

CriteriaBuilder builder = em.getCriteriaBuilder(); 
CriteriaQuery<String> query = builder.createQuery(String.class); 
Root<RuleVar> ruleVariableRoot = query.from(RuleVar.class); 
query.select(ruleVariableRoot.get(RuleVar_.varType)).distinct(true);