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.

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

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.

Oleksandr Bondarenko
  • 1,998
  • 1
  • 19
  • 22
  • 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. – wheeleruniverse Oct 23 '18 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 Sep 10 '20 at 07:42