CriteriaBuilder boolean comparison
Asked Answered
C

1

7

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.

Chrysostom answered 24/8, 2012 at 6:31 Comment(0)
A
17

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.

Alesiaalessandra answered 24/8, 2012 at 15:48 Comment(2)
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.Teem
To avoid NPE you can builder.equal(builder.coalesce(expression, false), flag);: this way NULL expression will be treated as FALSE.Yarvis

© 2022 - 2024 — McMap. All rights reserved.