I have a problem with using Conjunctions and Disjunctions. My program receives an arbitrary number of filter elements (each representing a Criterion) from the ui and is intended to chain together them as an AND or OR.
So for example I can have 3 elements like this (I represent a Criterion with a letter):
a OR b AND c
My code looks like this:
// ...
Criteria rootCriteria = createCriteria(entityClass);
Conjunction conjunction = Restrictions.conjunction();
Disjunction disjunction = Restrictions.disjunction();
boolean isFirst = true;
for (InternalFilterElement element : elements) {
if (isFirst) {
isFirst = false;
rootCriteria.add(createCriterion(element.getFilterRelation(), element.getValue()));
} else if (InternalFilterOperand.AND.equals(element.getInternalFilterOperand())) {
addCriterionToJunction(conjunction, element);
} else {
addCriterionToJunction(disjunction, element);
}
}
rootCriteria.add(disjunction);
rootCriteria.add(conjunction);
// ...
My problem is that I always get a AND b AND c and some unnecessary parentheses.
What I really wish to know is that I am using the wrong tool for this task or not? How can I mix AND and OR operators?
edit
InternalFilterOperand is basically an enum containing OR and AND
addCriterionToJunction just adds a Criterion to the Junction based on the relation (<, >, …) and the value. It does not have any side effects.
By using the following code, you mix AND and OR operators in Hibernate:
This example results in the following output: a=a OR b=b AND c=c without the parenthesis you would get with conjunction and disjunction.