JPA Pitfalls (7): Null Parameter

This blog article is part of a “series of blog articles” about common pitfalls using JPA and ways to avoid them. In this article, we describe issues with using null parameter values.

Setting the value of a query parameter to null leads to an unexpected query result: the query result is empty. The following JPQL query returns all employees for a given department, where the department is a query parameter:

SELECT e FROM Employee e WHERE e.department = :dept

You might think you could use the above query to retrieve employees without departments by setting the query parameter to null:

Query q = em.createQuery(
  "SELECT e FROM Employee e WHERE e.department = :dept");
q.setParameter("dept", null);
List<Employee> queryResult = q.getResultList();

But, JPQL follows the SQL NULL semantics and that means NULL is never equal to anything. This means even for an employee without department the WHERE clause evaluates to false and the result of the JPQL query is empty.

You should use the IS NULL or IS NOT NULL operator in JPQL in order to return all employees without a department:

Query q = em.createQuery(
  "SELECT e FROM Employee e WHERE e.department IS NULL");
List<Employee> queryResult = q.getResultList();

Recommendation: Use a IS NULL query when checking for null values in a JPQL query.

You can find an example of this pitfall and its solution in the class IsNullQueryExperiment in this project:

Leave a Reply