CriteriaBuilder boolean comparison

12,629

I suppose you implied using CriteriaBuilder's equal method. In this case yes, you can use it as follows:

builder.equal(expression, flag);

And this is equivalent to:

if (flag) {
  builder.isTrue(expression);
} else {
  builder.isFalse(expression);
}

But be aware that if you use Hibernate as JPA provider the former implementation will throw NPE in case expression==null is true while the latter one won't.

Share:
12,629
Jin Kwon
Author by

Jin Kwon

I'm a Java learner.

Updated on August 13, 2022

Comments

  • Jin Kwon
    Jin Kwon over 1 year

    I'm currently doing like this.

    final CriteriaBuilder builder = ...;
    final boolean flag = ...;
    
    if (flag) {
        builder.isTrue(expression);
    } else {
        builder.isFalse(expression);
    }
    

    Can I use it like this?

    builder.equals(expression, flag);
    

    Is this try won't have any problem? Say null for expression or something.

  • wheelerswebservices
    wheelerswebservices over 5 years
    When using this isTrue or isFalse I see that Hibernate is adding a =1 to my query . e.g. SELECT * FROM USER WHERE IS_ACTIVE = 1; Is there anyway that when using isTrue I can tell Hibernate to leave that =1 off as mySQL will treat boolean columns as true in condition by default? This additional =1 check is adding over 2 seconds to query when I have a 1 second SLA.
  • Ilario
    Ilario over 3 years
    To avoid NPE you can builder.equal(builder.coalesce(expression, false), flag);: this way NULL expression will be treated as FALSE.