Reputation: 726
I have to build a condition as below in the code. The number of conditions added as a mix of AND/OR may vary with the same parameters.
WHERE ( (name=? AND number=?) ) OR ( (name=? AND number=?) ) OR (...) OR (...)
I tried below code in a loop -- not working as expected:
someList.forEach(item -> {
SimpleExpression nameExp = Restrictions.eq("name", item.getName());
SimpleExpression numberExp = Restrictions.eq("number", item.getNumber());
Criterion criterion = Restrictions.and(nameExp, numberExp);
criteria.add(Restrictions.or(criterion));
}
With the code above, I am getting the output with AND in between the first condition and the second. I want OR between conditions 1 and 2.
WHERE ( (name=? AND number=?) ) AND ( (name=? AND number=?) )
How do I build the condition as mentioned at the top using the criteria?
Upvotes: 0
Views: 602
Reputation: 726
Here is the sample code for the general audience, based on the answer from Christian Beikov.
I have added additional conditions to my criteria to spruce up the solution.
criteria.add(
Restrictions.or(
Restrictions.and(criterionListB.toArray(new Criterion[0])),
Restrictions.or(criterionListA.toArray(new Criterion[0]))
));
This code evaluates to a mix of AND/OR operations as below:
(
(
(name = ? AND number = ?) OR (name = ? AND number = ?)
)
OR
(
(id = ? AND email = ?)
)
)
Upvotes: 0
Reputation: 16400
You collect the criterions to a list and finally invoke criteria.add(Restrictions.or(list))
.
Upvotes: 1