Search code examples
javaspringhibernatehibernate-criteriarestriction

Hibernate build query from List<Criterion> with or operators and dynamic Restrictions


I have a List that is feed programmatically according to some conditions, the code looks like this:

 List<Criterion> restrictionList = new ArrayList<Criterion>();
 for(int i = 1; i<someconditions.length);i++){          
        if( condition1){
           restrictionList.add(...);
        } else if(condition2){                      
           restrictionList.add(...)
        } else if(condition3){
            restrictionList.add(...)                
        }                   
    }       

And when building the Criteria, I did this:

for (int c = 0; c < restrictionList.size()-1;c++){
    crit.add(Restrictions.or(restrictionList.get(c),restrictionList.get(c+1)));
}

The where clause in the query string looks:

((A or B) AND (B or C))

since there is an And in the built clause, some of the results are not showing

Let's say I have records R1, R2 and R3

R1 meets conditions A and C R2 meets condition A R3 meets condition B and C

So (A or B) has R1,R2 and R3 (B or C) has R1 and R3

Since both conditions are bound by an AND, R2 is being left out of the final result

How can I make make the where clause to look like:

(A or B or C)

So the records can be displayed when they meet at least one condition.


Solution

  • if (!restrictionList.isEmpty()) {
        crit.add(or(restrictionList));
    }
    
    private Disjunction or(List<Criterion> restrictions) {
        Disjunction result = Restrictions.disjunction();
    
        for(Criterion restriction : restrictions) {
            result.add(restriction);
        }
    
        return result;
    }