1

我遇到了多个和/或条件的问题。情况就是这样,我有带有 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。

4

1 回答 1

2

Criteria API 已为您返回有效的有效 SQL。它在需要和我仔细阅读的地方添加了括号,我看不出它会在任何其他 RDBMS 上造成麻烦。

于 2013-06-07T07:45:05.883 回答