1

I need to compare a nullable entity property via IN expression within the following JPQL query:

@NamedQuery(name = "query", query = "SELECT e FROM MyEntity e WHERE e.status IN :statuses") 

Now, I like the shown collection-valued input parameter statuses to optionally contain null as an element:

final List<MyEntity> actual = entityManager.createNamedQuery("query", MyEntity.class) .setParameter("statuses", Arrays.asList(null, 1L)) .getResultList(); 

However with Hibernate/Derby an actual result list only contains entities with status 1L but not null.

I have not found anything in the JPA 2.2 specification about this case. Did I miss something or is this vendor-specific?


The answers to this question only solve part of my problem. In their proposed solutions, the null comparison is hard-baked into the query and cannot be controlled via the collection-valued parameter.

2
  • Does this answer your question? Checking for NULL on a Collection in JPQL queries? Commented Oct 4, 2021 at 11:10
  • @Yann39 Thank you, I also spotted this question. However, the answers only solve part of my problem. In their proposed solutions, the null comparison is hard-baked into the query and cannot be controlled via the collection-valued parameter. Commented Oct 4, 2021 at 12:00

1 Answer 1

2

As a Java programmer, where null = null yields true it might come as a surprise that in SQL (and JPQL) null = null is itself null which is "falsy". As a result, null in (null) yields null as well.

Instead you need to treat null seperately with a IS NULL check: e.status IS NULL OR e.status IN :statuses.

This is described in 4.11 Null Values of the JPA Specification:

  • Comparison or arithmetic operations with a NULL value always yield an unknown value.
  • Two NULL values are not considered to be equal, the comparison yields an unknown value.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that makes sense. I indeed had a different expectation of the ORM world here, however JPQL cannot modify the semantics of SQL. For my specific case, this means that I need to introduce two corresponding JPQL queries (one with ... IS NULL OR ... and a second without) and decide on the Java side which one to call, right?
Yes, I am afraid so!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.