简体   繁体   English

具有 AND/OR 组合的休眠条件

[英]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.作为 AND/OR 混合添加的条件数量可能因相同的参数而异。

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.使用上面的代码,我在第一个条件和第二个条件之间使用 AND 获得输出。 I want OR between conditions 1 and 2.我想要条件 1 和 2 之间的 OR。

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.以下是针对一般观众的示例代码,基于 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:此代码评估为混合 AND/OR 操作,如下所示:

(
  (
    (name = ? AND number = ?) OR (name = ? AND number = ?)
  ) 
  OR 
  (
    (id = ? AND email = ?)
  )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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