46

How can I express literal true and literal false in JPA's Criteria API?

I'm looking for something like Predicate alwaysTrue = CriterialBuilder.DefaultLiterals.TRUE (analogous to java.lang.Boolean.TRUE).

Abdull
  • 26,371
  • 26
  • 130
  • 172

3 Answers3

71

To get an always true Predicate instance, use criteriaBuilder.and().
To get an always false Predicate instance, use criteriaBuilder.or().

Michal Foksa
  • 11,225
  • 9
  • 50
  • 68
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • `javax.persistence.criteria.Predicate always = true;` results in `Type mismatch: cannot convert from boolean to Predicate`. – Abdull Feb 03 '13 at 17:50
  • 4
    `CriteriaBuilder.and()` returns an always true predicate. http://docs.oracle.com/javaee/6/api/javax/persistence/criteria/CriteriaBuilder.html#and%28javax.persistence.criteria.Predicate...%29 – JB Nizet Feb 03 '13 at 17:52
  • ... and for a `Predicate` instance that always evaluates to `false`, one can use `javax.persistence.criteria.Predicate alwaysFalse = aCriteriaBuilder.and().not()` ... what where the API designers thinking?! – Abdull Feb 03 '13 at 18:02
  • 6
    You can use `CriteriaBuilder.or()`. I also find this API awful. – JB Nizet Feb 03 '13 at 18:03
  • @JBNizet Are those `and()` and `or()` equivalent to `conjunction()` and `disjunction()`, respectively? Thanks. – Jin Kwon Dec 19 '19 at 02:27
30

CriteriaBuilder#conjunction() returns a TRUE predicate.

CriteriaBuilder#disjunction() returns a FALSE predicate.

/**
 * Create a conjunction (with zero conjuncts).
 * A conjunction with zero conjuncts is true.
 *
 * @return and predicate
 */
Predicate conjunction();

/**
 * Create a disjunction (with zero disjuncts).
 * A disjunction with zero disjuncts is false.
 *
 * @return or predicate
 */
Predicate disjunction();
Patrick Garner
  • 3,201
  • 6
  • 39
  • 58
  • Are those methods equivalent to `and()` and `or()`, respectively? And actually are the right way to do? Thanks. – Jin Kwon Dec 19 '19 at 02:26
  • 1
    No, `conjunction()` and `disjunction()` do not take arguments like `and()` and `or()` do. `conjunction()` returns only a true predicate whereas `and()` can return either a true or false predicate, depending on its arguments. Similarly, `disjunction()` returns only a false whereas `or()` can return a true or false, depending on its arguments. – Patrick Garner Dec 19 '19 at 13:00
14

Although the other answers solve the problem, I think they don't show the intention of the code, which should be "an always true predicate".

Personally I think the approach below is more clear, although a bit longer.

Always true

criteriaBuilder.isTrue(criteriaBuilder.literal(true));

Always false

criteriaBuilder.isFalse(criteriaBuilder.literal(true));
Johnny Willer
  • 3,717
  • 3
  • 27
  • 51