java - 带 null 参数的 Spring Boot 原生查询

标签 java spring-boot spring-data-jpa

我在 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/

相关文章:

java - 如何更正 Spring Boot 应用程序的类路径,使其包含单个兼容版本的 javax.persistence.PersistenceContext?

java - 为什么我的代码中总是出现找不到符号方法错误?

java - Play框架,for循环内的动态语句

java - Maven 3 : Failed to execute goal org. apache.maven.plugins :maven-archetype-plugin:2. 2:生成

java - 在这种情况下是否可能出现浮点错误?

java - Tomcat 中的 Quartz 调度程序内存泄漏

java - 无法将投影添加到 envers 查询中的关系字段

java - Spring 数据 JPA : How to execute aggregate functions

java - 由 : org. hibernate.PropertyNotFoundException 引起:无法在类上找到字段名称

java - Swagger 文档中未显示嵌套对象