我在Spring Boot中有一个本地查询,
@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,它可以为null。当我使用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上搜索了类似的问题,并遵循了一些建议,但仍然无法正常工作。有什么想法吗?
答案 0 :(得分:4)
我遇到了一个同样的问题,我设法通过将其强制转换为BIGINT,但首先是TEXT,然后是BIGINT来解决它。我使用的是Spring Boot 2.2和Kotlin,但是对于Java来说却一样。
我有以下示例:
sizeof(cl_mem)
如果我不进行转换,则会出现错误:
@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>
我只将它强制转换为BIGINT,然后错误是:
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
答案 1 :(得分:0)
您可能有两个不同的查询来处理Null和Not Null。根据位置为空或不为空调用这两个方法
@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 ) " +
"LIMIT ?4", nativeQuery = true)
@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 is null) " +
"LIMIT ?4",
nativeQuery = true)
答案 2 :(得分:0)
只需反向查询中的参数即可。
@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 ( ?3 is null or t.location_1 = ?3) " +
"LIMIT ?4",
nativeQuery = true)
List<Transaction> findBySearchTerms(@Param("fromDateTime") String fromDateTime,
String toDateTime,
Integer location1,
Integer maxCount
);