簡體   English   中英

Criteria query combine and predicates and or 謂詞在 where 方法中

[英]Criteria query combine and predicates and or predicates in where method

CriteriBuilder的where方法

根據指定的限制謂詞的合取來限制查詢結果

換句話說,用 AND 連接所有謂詞。 我以這種方式將謂詞列表傳遞給此方法:

criteria.where(preds.toArray(new Predicate[0]));

結果查詢是這樣的:

... where p1 and p2 and p3

但是我需要的是:

... where p1 and p2 or p3

我嘗試使用兩個預測列表,一個用於“ANDS”,另一個用於“ORS”:

if(preds.isEmpty() && !orPreds.isEmpty()) {
    criteria.where(cb.or(orPreds.toArray(new Predicate[orPreds.size()])));
}
else if(!preds.isEmpty() && !orPreds.isEmpty()) {
    criteria.where(cb.and(preds.toArray(new Predicate[preds.size()])), 
    cb.or(orPreds.toArray(new Predicate[orPreds.size()])));
}
else {
    criteria.where(preds.toArray(new Predicate[0]));
}

但是結果查詢是一樣的:

... where p1 and p2 and p3

任何的想法?

只需使用CriteriaBuilder.and(Predicate... restrictions)CriteriaBuilder.or(Predicate... restrictions)將謂詞數組組合為簡單謂詞

為了獲得where (p1 and p2) or p3 ,其中p1p2p3都是與and語句連接的謂詞數組:

Predicate[] p1 = new Predicate[2];
Predicate[] p2 = new Predicate[2];
Predicate[] p3 = new Predicate[2];
// add your predicates to the arrays.     
Predicate p1all = cb.and(p1);    
Predicate p2all = cb.and(p2);
Predicate p3all = cb.and(p3);
Predicate pFinal = cb.or(cb.and(p1all, p2all), p3all);
criteria.where(pFinal);

為了獲得where p1 and (p2 or p3)

Predicate pFinal = cb.and(cb.or(p2all, p3all), p1all);
criteria.where(pFinal);

最后,如果要通過將謂詞數組與or語句連接來構建單個謂詞,請使用以下命令:

Predicate p1all = cb.or(p1); 

默認情況下,所有謂詞都被理解為“AND”。

您可以“玩”使用 cb.and / cb.or 為謂詞增加更多復雜性(如果需要嵌套)

您可以像這樣創建一個列表:

Root<BeanA> queryRoot = cq.from(BeanA.class);

List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(queryRoot.get("id"), valueA);
predicates.add(cb.or(
                cb.equal(queryRoot.get("id"), valueA,
                cb.equal(queryRoot.get("id"), valueB
        ));
predicates.add(cb.and(
       cb.equal(queryRoot.get("valueC"), valueC),
       cb.or(
             cb.equal(queryRoot.get("id"), valueA,
             cb.equal(queryRoot.get("id"), valueB
        ))
);

cq.where(predicates.toArray(Predicate[]::new));

如果需要,您也可以使用多選(如果要處理子查詢,請在此處添加子查詢的結果)

 List<Selection> selectList = new ArrayList<>();

 selectList.add(queryRoot.get("id"));
 selectList.add(queryRoot.get("title"));

 cq.multiselect(selectList.toArray(Selection[]::new));

添加多選后,您可能需要一個 orderBy。 您可以遵循相同的概念,但使用表達式列表

List<Expression> groupByList = new ArrayList<>();

groupByList.add(proyectoJoin.get("id"));
groupByList.add(proyectoJoin.get("title"));
 
cq.groupBy(groupByList.toArray(Expression[]::new));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM