Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot native query with null parameter

I have a native query in Spring Boot as such:

@Query(value = "SELECT t.* FROM Transaction t WHERE " +
    "t.datetime >= TO_TIMESTAMP(?1,'YYYY-MM-ddTHH:MI') " +
    "AND t.datetime < TO_TIMESTAMP(?2,'YYYY-MM-ddTHH:MI') " +
    "AND (t.location_1 = ?3 or ?3 is null) " +
    "LIMIT ?4",
    nativeQuery = true)
    List<Transaction> findBySearchTerms(@Param("fromDateTime") String fromDateTime,
            String toDateTime,
            Integer location1,
            Integer maxCount
            );

For the location1, it may be null. When i run this query with location1 null, it returns the error message: org.postgresql.util.PSQLException: ERROR: operator does not exist: bigint = bytea

After which i tried casting on parameter 3:

"AND (?3 is null or t.location_1 = cast(?3 as bigint)) " +

It also results in an error: org.postgresql.util.PSQLException: ERROR: cannot cast type bytea to bigint.

I have searched for similar questions on stackoverflow and followed some of the recommendations but it still does not work. Any ideas?

like image 471
Eugene Avatar asked Apr 16 '26 03:04

Eugene


1 Answers

I had a same issue and I managed to fix it by casting it to BIGINT but first to TEXT and then BIGINT. I use Spring Boot 2.2 and Kotlin, but same is for Java.

I have following example:

 @Query(
        """
         SELECT
         f.id,
         f.name,
         c.id AS company_id,
         c.name AS company_name
         FROM facility f
         WHERE (:companyId IS NULL OR f.company_id = CAST(CAST(:companyId AS TEXT) AS BIGINT))  
        """
)
@Transactional(readOnly = true)
    fun exampleMethod(@Param("companyId") companyId: Long? = null):List<Result>

If I do not cast it I get error:

Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: bigint = bytea
  Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts

and I I cast it just to BIGINT once, then error is:

Caused by: org.postgresql.util.PSQLException: ERROR: cannot cast type bytea to bigint
like image 62
codemozzer Avatar answered Apr 18 '26 15:04

codemozzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!