2014-06-19 44 views
2

要求:有一些初始條件。小程序說P1是謂詞。 數據庫表中有一個可以爲空的日期字段。如果它爲空,我可以繼續使用初始謂詞本身。如果它不爲null,則該字段的值必須在指定的日期之間。JPA標準查詢中的複合謂詞 - 同時使用和/或方法

方法1: 我想在我的查詢中使用'和''或'條件。問題在於謂詞的組合。

Predicate P1 = criteriaBuilder.equal(a,b); 
Predicate P2 = criteriaBuilder.isNull(myDate); 
Predicate P3 = criteriaBuilder.isNotNull(myDate); 
Predicate P4 = criteriaBuilder.between(currentDate,previousDate); 


Predicate P34 = criteriaBuilder.and(P3,P4); 
Predicate P234 = criteriaBuilder.or(P2,P34); 
Predicate P1234 = criteriaBuilder.and(P1,P234); 
criteriaBuilder.where(P1234); 
查詢

預期條件:P1(P2OR(P3和P4))查詢

實際情況:P1和P2或P3和P4

Approach2:使用一些數學集合論並展開括號。

Predicate P12 = criteriaBuilder.and(P1,P2); 
Predicate P34 = criteriaBuilder.and(P3,P4); 
Predicate P134 = criteriaBuilder.and(P1,P34); 
Predicate P12134 = criteriaBuilder.or(P12,P134); 
criteriaBuilder.where(P12134); 

在查詢的預期條件:(P1和P2)OR(P1和P3以及P4)在查詢

實際條件:P1和P2或P1和P3以及P4

在這兩個方法我缺少括號。建議我得到這些括號的方法。有沒有更好的方法來滿足要求?

回答

1

在這兩種情況下,預期條件和實際條件是等效的。表達式從左到右進行評估,並且AND優先於OR

看你的第一個查詢,既沒有括號,下面的組合產生真實的,而其他的都會產生錯誤:

SELECT true AND true OR true AND true; 
SELECT true AND false OR true AND true; 
SELECT true AND true OR false AND false; 

SELECT true AND (true OR (true AND true)); 
SELECT true AND (false OR (true AND true)); 
SELECT true AND (true OR (false AND false)); 
+0

公牛眼睛...感謝@Robby Cornelissen。但我認爲,作爲每種方法1:預期的和實際的不會得出與你的解釋相同的結果。但是,我得到了我正在尋找的東西。 – tortoise