简体   繁体   中英

Criteria Builder does not return an entity when nested entity is null

I have a root entity "caseHeader" that have some nested entities (--> activeCase --> customer). I am using a criteria builder to dynamically search over those entities. I am trying to create a predicate that will match several fields including one of the fields of the nested entity (client). So I tried something like this:

criteriaBuilder.or(
  criteriaBuilder.equal(caseHeaderRoot.get("id"), "1234"),
  criteriaBuilder.equal(caseHeaderRoot.get("activeCase").get("customer").get("uniqueId"), "1234")
)

Well, if the customer is not null, then this works as expected. It returns entities with id or customer unique id equal to "1234". But if there is an entity with id "1234" and no customer, this entity is not included in the result set, even though the first predicate should match it.

I tried to check for null customer like this:

criteriaBuilder.or(
  criteriaBuilder.equal(caseHeaderRoot.get("id"), "1234"),
  criteriaBuilder.and(
    criteriaBuilder.isNotNull(caseHeaderRoot.get("activeCase").get("customer")),
    criteriaBuilder.equal(caseHeaderRoot.get("activeCase").get("customer").get("uniqueId"), "1234")
  )
)

I tried also to use the meta-model instead of the strings, to avoid typos in my model, but the result was the same.

What am I missing? Why the null customer makes the query to not match that entity even though the root entity ID would match the first predicate.

I have found out what it was, in case someone fall into the same trap, here is how I fixed it...

Now I join the root with left joins for the activeCase and customer like this:

Join customerJoin = caseHeaderRoot.join("activeCase", JoinType.LEFT).join("customer", JoinType.LEFT);
criteriaBuilder.or(
  criteriaBuilder.equal(caseHeaderRoot.get("id"), "1234"),
  criteriaBuilder.equal(customerJoin.get("uniqueId"), "1234")
)

I think this could help also others. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM