I have the following code in Hibernate Query Language:
@Query("SELECT a FROM Table a " +
"WHERE (COALESCE(:param, null) IS NULL OR a.value in :param) "
)
List<InspectionInstruction> findAllInIds(@Param("param") List<Long> ids);
The call is either with a List of Ids, or just with null. So I want to use the where clause if the list is not empty, if it is empty, I want to omit the where clause. The actual query is much bigger and has multiple clauses, so splitting them up is not a viable option.
It works great with MySQL (Version 8), however using it with H2, I get the following error:
WARN [http-nio-auto-1-exec-4] --- o.h.e.j.s.SqlExceptionHelper: SQL Error: 50004, SQLState: HY004
ERROR [http-nio-auto-1-exec-4] --- o.h.e.j.s.SqlExceptionHelper: Unknown data type: "NULL, ?"; SQL statement:
select a0_.id as col_0_0_ from table a0_ where coalesce(?, null) is null or a0_.id in (?) [50004-214]
My H2 connection string:
url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL
driverClassName: org.h2.Driver
Is there a way of handling possible null values as param in H2? I could also pass an empty list instead of null, if that has any advantage.
Not the answer I was looking for, but one that works:
I played around with some CriteriaBuilder
implementation but as HQL is used throughout the entire project and I also like to write HQL statements because they are close to SQL, I ended up doing it like this:
@Query("SELECT a FROM Table a " +
"WHERE (:paramEmpty IS TRUE OR a.value in :param) "
)
List<InspectionInstruction> findAllInIds(@Param("param") List<Long> ids, @Param("paramEmpty") boolean idsEmpty);
Which is a bit of an ugly method in my opinion, but it does the job.
I also found the size() function, got excited, but it doesn't support parameters.