简体   繁体   中英

Hibernate criteria with a combination of AND/OR

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?

您将标准收集到一个列表中,最后调用criteria.add(Restrictions.or(list))

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 = ?)
  )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM