Hibernate 6 not handling null query parameter in native query

110 views Asked by At

I am migrating from Spring Boot 2.7 to 3.2 and while trying to run a native query using Spring Data and Hibernate, i end up with the following error:

Caused by: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [    
    SELECT *
      FROM myTable
      WHERE (? IS NULL OR my_first_field like ? || '%')
        AND (? IS NULL OR my_second_field like ? || '%')
    LIMIT ?
] [ERROR: could not determine data type of parameter $3] [n/a]

In my JpaRepository, the query is like following:

@Query(
      value =
          """
          SELECT *
              FROM myTable
              WHERE (:myFirstField IS NULL OR my_first_field like :myFirstField || '%')
                  AND (:mySecondField IS NULL OR my_second_field like :mySecondField || '%')
          LIMIT :limit
      """,
      nativeQuery = true)
  List<MyTableEntity> getEntitiesWhereFirstAndSecondFieldsLike(
      @Param("myFirstField") String myFirstField,
      @Param("mySecondField") String mySecondField,
      @Param("limit") int limit);

In this case, the error is triggered by the parameter 'mySecondField' being null.

This exact same query worked perfectly fine in Spring Boot 2.7 and i feel like i have read the whole migration guide without finding any clue.

Is there a anything i can set to tell Hibernate how to deal with null values ?

Running the SQL query against my database (which is PostgreSql) and replacing ':myFirstField' and ':mySecondField' with null also works, if that helps.

Casting parameters (as below) seems to fix the issue, but i can not do that for every native query in my application as that might take me quite some time and doesn't feel like the right solution at all.

SELECT *
    FROM myTable
    WHERE ((:myFirstField as text) IS NULL OR my_first_field like :myFirstField || '%')
        AND ((:mySecondField as text) IS NULL OR my_second_field like :mySecondField || '%')
LIMIT :limit
0

There are 0 answers