我遇到了多个和/或条件的问题。情况就是这样,我有带有 user、dateFrom 和 dateTo 字段的 WorkTime 实体,以及带有 organizationUnit 字段的 User 实体。我正在构建以下查询以获取日期之间的工作时间,包括与这些日期重叠的日期:
// main condition to get only users from given organizational unit
Predicate restriction = root.get(WorkTime_.user).get(User_.organizationalUnit).in((Object[]) orgUnits);
// first date condition to get work time between border dates
Predicate dateInRestr = builder.greaterThanOrEqualTo(root.get(WorkTime_.dateFrom), dateFrom);
dateInRestr = builder.and(dateInRestr, builder.lessThanOrEqualTo(root.get(WorkTime_.dateTo), dateTo));
// second date condition to get work time overlap border dates
ParameterExpression<Date> dateFromParam = builder.parameter(Date.class);
ParameterExpression<Date> dateToParam = builder.parameter(Date.class);
Predicate dateOutRestr = builder.between(dateFromParam, root.get(WorkTime_.dateFrom), root.get(WorkTime_.dateTo));
dateOutRestr = builder.or(dateOutRestr, builder.between(dateToParam, root.get(WorkTime_.dateFrom), root.get(WorkTime_.dateTo)));
// OR for dates condition
Predicate dateRestr = builder.or(dateInRestr, dateOutRestr);
// AND with unit condition
query.where(restriction, dateRestr);
通常它可以正常工作,但 PostgreSQL 中的查询结果如下所示(仅显示条件部分):
and (user1_.ORG_UNIT_ID in (? , ? , ? , ? , ? , ?))
and (worktime0_.DATEFROM>=? and worktime0_.DATETO<=?
or ? between worktime0_.DATEFROM and worktime0_.DATETO
or ? between worktime0_.DATEFROM and worktime0_.DATETO)
是否有机会在 OR 条件元素周围添加额外的括号,以便查询如下所示:
and (user1_.ORG_UNIT_ID in (? , ? , ? , ? , ? , ?))
and ((worktime0_.DATEFROM>=? and worktime0_.DATETO<=?)
or (? between worktime0_.DATEFROM and worktime0_.DATETO)
or (? between worktime0_.DATEFROM and worktime0_.DATETO))
或者从 SQL 的角度来看没关系?我担心它不适用于其他 RDMBS。