2011-03-13 43 views
1

在做基於字符串的查詢,可以使用「身份證」的關鍵字上多到一個屬性如:CriteriaBuilder多到一個限制的ID

from Enrolment where person.id=:personId 

在這種情況下,這將產生sql:

select * from enrolment where person_id=? 

如何使用CriteriaBuilder實現相同?

CriteriaQuery<Enrolement> query = criteriaBuilder.createQuery(Enrolement.class); 
Root<Enrolement> root = query.from(Enrolment.class); 
query.select(root); 

// Does not work 
query.where(criteriaBuilder.equal(root.get("person.id"), 1L)); 

// Does not work 
query.where(criteriaBuilder.equal(root.get("person").root.get("personId"), 1L)); 

我想你可以加入到人,並添加一個限制的人根但在我看來是矯枉過正。

回答

0

試錯後了以下工作:

query.where(criteriaBuilder.equal(root.get("person"), 1L)); 

我想我一直在寫基於字符串的查詢,這麼長時間我看不到樹木,不見森林。這將是很好,如果編寫查詢的兩種方法是一致的:

from Enrolement where person=1L (does not work) 
+0

你試過query.where(criteriaBuilder.equal(root。 get(「person.id」),1L));和query.where(criteriaBuilder.equal(root.get(「person」)。get(「personId」),1L)); – Koitoer 2014-01-24 23:39:17

1

這在類似的設置爲我工作:

criteriaBuilder.equal(datasheetRoot.get(Datasheet_.componentSubtype) 
            .get(ComponentSubtype_.id), 
         componentSubtypeId); 

(這是使用Spring 1.0.1啓動與Spring JPA數據1.5.1和4.3.1休眠)

我的根是Datasheet具有@ManyToOneComponentSubtype這反過來又具有id