如何处理 Spring 数据 jpa 和 jpql 查询中非必需参数的 PSQLException upper(bytea) 问题

How to handle PSQLException upper(bytea) problem on non-required parameter in Spring data jpa & jpql Query

我在 Spring 存储库中有此请求

    @Query("Select l from Loan l WHERE (:status is null or l.currentStatus = upper(:status)) and (:id is null or  l.user.id = :id)")
    List<Loan> findByCurrentStatusAndUserId(@Param("status") String status, @Param("id")Long id);

假设参数为 null 时忽略它们,除了它向我发送一个 :

org.postgresql.util.PSQLException: ERREUR: la fonction upper(bytea) n'existe pas
(function upper(bytea) doesn't exists)

如果我的状态参数为空。 这对我来说没有意义。如果它为空,则不应对其进行测试,这就是放置“:status is null”否的全部意义所在? 我如何在不在我的业务层中设置大条件来测试我的参数的情况下处理这个问题?

你的问题是你在 null 参数上使用 upper 函数,因为 postgreSql 像 upper(null) 一样解释它,不管你的 null 条件如何,查询中有一些没有解决方案的相关问题,所以我建议您在列中应用上部(不是参数)并将上部句子添加到 java:

中的参数
@Query("Select l from Loan l WHERE (:status is null or upper(l.currentStatus) = :status) and (:id is null or  l.user.id = :id)")
List<Loan> findByCurrentStatusAndUserId(@Param("status") String status, @Param("id")Long id);

正如我刚才所说,如果您在调用此查询之前在参数中设置 upper,它应该可以工作。

(您可以通过删除查询中的 upper 并再次发送空值来验证此问题)