2010-11-17 131 views
6

我無法弄清楚如何創建這樣與Hibernate條件的查詢synthax休眠條件查詢 - 嵌套條件

select * from x where x.a = 'abc' and (x.b = 'def' or x.b = 'ghi') 

你有如何做到這一點的想法?
我使用Hibernate Restriction靜態方法,但我不明白如何指定嵌套'或'條件

回答

13

您特定的查詢可能是:

crit.add(Restrictions.eq("a", "abc")); 
crit.add(Restrictions.in("b", new String[] { "def", "ghi" }); 

如果你想知道關於一般AND和OR,這樣做:

// Use disjunction() or conjunction() if you need more than 2 expressions 
Disjunction aOrBOrC = Restrictions.disjunction(); // A or B or C 
aOrBOrC.add(Restrictions.eq("b", "a")); 
aOrBOrC.add(Restrictions.eq("b", "b")); 
aOrBOrC.add(Restrictions.eq("b", "c")); 

// Use Restrictions.and()/or() if you only have 2 expressions 
crit.add(Restrictions.and(Restrictions.eq("a", "abc"), aOrBOrC)); 

這將等同於:

where x.a = 'abc' and (x.b = 'a' or x.b = 'b' or x.b = 'c') 
+0

非常有幫助謝謝 – mickthompson 2010-11-18 09:22:12

1

使用更像(x.b IN ('def', 'ghi'))的語法。