oulenz
oulenz

Reputation: 1244

How does CriteriaBuilder.equal() treat null values?

I expected CriteriaBuilder.equal(Expression<?> x, Object y) to always evaluate to false when y is null, but to my surprise that's not what happens: it evaluates to true for rows where the relevant field is also null (I've only tested this for Strings).

The only thing I've been able to find on this is this explanation, which corresponds to my mistaken initial assumption.

What is really happening here? Is CriteriaBuilder.equal(Expression<?> x, Object y) transformed into CriteriaBuilder.isNull(Expression<?> x) when y is null? Are null Strings transformed to 'null'? Or am I somehow mistaken?

Upvotes: 1

Views: 3408

Answers (2)

degr
degr

Reputation: 1565

I use criteria builder, and it was not smart enough to replace = with "is null". So, I did something similar to this one:

 reportRepo.findAll((r, q, cb) -> parentId == null
                      ? cb.isNull(r.get(Report.Fields.parentId))
                      : cb.equal(r.get(Report.Fields.parentId), parentId))

Upvotes: 0

Chris
Chris

Reputation: 21165

It is provider specific, but EclipseLInk can tell that your parameter is null and so turn the equality check into an isNull check when it creates the expression from the criteria query. This is not the case if you are using parameters, as the expression may be prepared before the parameter is passed in.

Upvotes: 3

Related Questions