【问题标题】:compound predicate in JPA Criteria Query - Use both and, or methodsJPA Criteria Query中的复合谓词-同时使用and,or方法
【发布时间】:2014-08-10 12:15:38
【问题描述】:

要求:有一些初始条件。假设 P1 是谓词。 数据库表中有一个可能为空的日期字段。如果它为空,我可以继续初始谓词本身。如果它不为空,则该字段的值必须在指定日期之间。

方法1: 我正在尝试在查询中同时使用“和”“或”条件。问题在于谓词的组合。

Predicate P1 = criteriaBuilder.equal(a,b);
Predicate P2 = criteriaBuilder.isNull(myDate);
Predicate P3 = criteriaBuilder.isNotNull(myDate);
Predicate P4 = criteriaBuilder.between(currentDate,previousDate);


Predicate P34 = criteriaBuilder.and(P3,P4);
Predicate P234 = criteriaBuilder.or(P2,P34);
Predicate P1234 = criteriaBuilder.and(P1,P234);
criteriaBuilder.where(P1234);

查询中的预期条件:P1 AND (P2 OR (P3 AND P4))

查询中的实际条件:P1 AND P2 OR P3 AND P4

方法2:使用一些数学集合论并展开括号。

Predicate P12 = criteriaBuilder.and(P1,P2);
Predicate P34 = criteriaBuilder.and(P3,P4);
Predicate P134 = criteriaBuilder.and(P1,P34);
Predicate P12134 = criteriaBuilder.or(P12,P134);
criteriaBuilder.where(P12134);

查询中的预期条件:(P1 AND P2) OR (P1 AND P3 AND P4)

查询中的实际条件:P1 AND P2 OR P1 AND P3 AND P4

在这两种方法中,我都缺少括号。建议我获得这些括号的方法。有没有更好的方法来满足要求??

【问题讨论】:

    标签: jpa criteria predicate criteria-api


    【解决方案1】:

    在这两种情况下,预期条件和实际条件是等价的。表达式从左到右计算,AND 优先于OR

    查看您的第一个查询,无论是否有括号,以下组合产生真,而所有其他组合产生假:

    SELECT true AND true OR true AND true;
    SELECT true AND false OR true AND true;
    SELECT true AND true OR false AND false;
    
    SELECT true AND (true OR (true AND true));
    SELECT true AND (false OR (true AND true));
    SELECT true AND (true OR (false AND false));
    

    【讨论】:

      猜你喜欢
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 2011-12-28
      • 2020-10-17
      • 1970-01-01
      相关资源
      最近更新 更多