Pretty new with JPA Query
I am assigned to retrieve data from a postgresql database table, with three cases:
- either a certain field has value or not
- if a field has value
- if a field has not value
I use a Boolean requestparam that can either be true
, false
or null
and use it to query from the repository
At first, I separated the repository queries but for performance reasons, I am tasked to use only one repository query, using the @Query
annotation
I am trying to use CASE WHEN
without much success, here is what I came up with so far
@Query("SELECT e FROM Elements e"
+ " WHERE e.fieldOfInterest = "
+ " CASE WHEN :parameter IS NULL e.fieldOfInterest"
+ " WHEN :parameter = true THEN NOT NULL
+ " ELSE NULL END")
List<Elements> findWithNullableParam(@Param("parameter") Boolean parameter);
And I'm hit with the following error when compiling
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: NOT near line 1, column 161
I am aware that a WHERE field = NOT NULL
will not be okay
I am considering using NULLIF() in my CASE block but I have no idea how it works yet
How do I formulate the query for my conditions to be met?