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.
Comments
-
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 over 5 yearsWhen 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 over 3 yearsTo avoid NPE you can
builder.equal(builder.coalesce(expression, false), flag);
: this way NULL expression will be treated as FALSE.