我在 Spring Boot 中有一个 native 查询,如下所示:
@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
);
对于location1,它可能为空。当我使用 location1 null 运行此查询时,它返回错误消息:org.postgresql.util.PSQLException:错误:运算符不存在:bigint = bytea
之后我尝试对参数 3 进行转换:
"AND (?3 is null or t.location_1 = cast(?3 as bigint)) " +
它还会导致错误:org.postgresql.util.PSQLException:错误:无法将类型 bytea 转换为 bigint。
我在 stackoverflow 上搜索了类似的问题并遵循了一些建议,但仍然不起作用。有什么想法吗?
最佳答案
我遇到了同样的问题,我设法通过将其转换为 BIGINT 但首先转换为 TEXT,然后转换为 BIGINT 来解决它。我使用 Spring Boot 2.2 和 Kotlin,但 Java 也是如此。
我有以下示例:
@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>
如果我不转换它,我会收到错误:
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
我将它转换为 BIGINT 一次,然后错误是:
Caused by: org.postgresql.util.PSQLException: ERROR: cannot cast type bytea to bigint
关于java - 带 null 参数的 Spring Boot 原生查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267049/