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.

1 Answer 1

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.

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. Commented Oct 23, 2018 at 18:58
  • To avoid NPE you can builder.equal(builder.coalesce(expression, false), flag);: this way NULL expression will be treated as FALSE.
    – Ilario
    Commented Sep 10, 2020 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.