2010-05-21 46 views
7

此問題與this one非常相似,但對這個問題的回答是最小的。Hibernate標準查詢可以與所有子集合元素匹配

我有一個父類與一組子實體。子實體只是一個字符串的包裝,並且與父實體位於不同的表中。我想有一個標準查詢,當子組實體的所有成員都返回一個條件時返回父實體。此條件與字符串列表中的一個匹配。下面是我在哪裏:

Criteria c = criteria(); 
Criteria ands = c.createCriteria("ands"); 
Disjunction dis = Restrictions.disjunction(); 
for (String value : values) { 
    dis.add(Restrictions.like("value", "%" + value + "%")); 
} 
ands.add(dis); 
return list(c); 

「阿富汗國家發展戰略」是一個「值」字段是一個字符串的實體集。 「criteria()」爲父類創建一個標準。 「list()」只是調用criteria.list();

這只是匹配任何元素,而不是全部。

希望這是有道理的。任何幫助非常感謝。

回答

0

那不應該是連詞?

+0

嗨, 它需要一個析取,因爲我要選擇父那裏集合中的所有元素都喜歡的方式字符串a或字符串b或字符串c。等等。 – 2010-05-23 16:44:37

3

作爲一種理論上的做法,你可以做這樣的事情:

Criterion condition = ...; 

Criteria c = s.createCriteria(Parent.class, "p"); 
DetachedCriteria dc = DetachedCriteria.forClass(Parent.class, "p2") 
    .createCriteria("ands", "c") 
    .add(Restrictions.not(condition)) 
    .add(Property.forName("p.id").eqProperty("p2.id")) 
    .setProjection(Projections.id()); 

c.add(Subqueries.notExists(dc)); 

然而,這種方法是不適合實際使用,因爲它需要額外的join(由於沒有在標準API in elements條款)。另請注意,它使用雙重否定(SELECT ... WHERE NOT EXISTS (SELECT ... WHERE NOT <condition>)),所以它可能與NULL有問題。

編輯:在HQL可以這樣寫:

from Parent p 
where not exists (select c from p.ands c where not <condition>) 

from Parent p 
where not exists (select c from Child c 
    where not <condition> and c in elements(p.ands)) 

但是,據我瞭解,這兩個查詢不能在標準API表示(你不能在子查詢中寫from p.ands,不能使用in elements)。所以,在標準的API,你必須使用額外的連接(注2個Parent S):

from Parent p 
where not exists (select c from Parent p2 join p2.ands c 
    where not <condition> and p = p2) 
+0

謝謝你。只是探索其可能性。也許HQL在這裏會更好,但我無法理解elements()子句。我可以以某種方式使用所有元素(parent.ands)嗎? – 2010-05-23 16:46:34

+0

@Andrew:編輯 – axtavt 2010-05-23 17:34:35

+0

啊 - 很酷。這按預期工作。非常感謝。現在只關心表現。 – 2010-05-23 19:24:46

相關問題