2017-04-10 3 views
0

Procédé where de CriteriBuilderCritères requête combiner et prédicats et ou prédicats dans lequel procédé

limite le résultat de la requête en fonction de la combinaison de la restriction spécifiée prédicats

En d'autres termes, concaténer toutes prédicats avec AND. Je passe une liste de prédicats à cette méthode de cette façon:

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

La requête de résultat quelque chose comme ceci:

... where p1 and p2 and p3 

cependant ce que j'ai besoin est:

... where p1 and p2 or p3 

J'ai essayé pour utiliser deux listes de prédicats, un pour "ANDS" et un autre pour "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])); 
} 

Mais la requête de résultat est le même:

... where p1 and p2 and p3 

Toute idée?

+0

Que voulez-vous dire par 'où p1 et p2 ou p3'? 'où (p1 et p2) ou p3'? 'où p1 et (p2 ou p3)'? – perissf

Répondre

0

simplement votre tableaux de prédicats dans prédicats simples, en utilisant CriteriaBuilder.and(Predicate... restrictions) et CriteriaBuilder.or(Predicate... restrictions)

Pour obtenir where (p1 and p2) or p3, où p1, p2 et p3 sont tous les tableaux de prédicats concaténés avec and déclarations:

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); 

Pour obtenir where p1 and (p2 or p3):

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

Enfin, si vous voulez construire un seul prédicat en enchaînant un tableau de prédicats avec or déclarations, utilisez ceci:

Predicate p1all = cb.or(p1);