spring-boot - 表达式为空会导致 native 查询出现异常

标签 spring-boot hibernate spring-data-jpa

我使用HibernateJpaRepository处理我的数据库操作。

我有这个查询(为了简化,因为原始查询相当大):

@Query(value="select * from history h where h.project_id in :projects", nativeQuery=true)
List<History> getHistoriesByProjectsIn(@Param("projects")List<Long> projects);

当我通过有效且非空 List<Long> 时它正在工作。但是,当我传递可能发生的空列表时,这在我的场景中并不罕见,我得到:

org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"

谁能告诉我如何摆脱它吗?

最佳答案

postgresql 文档 states : in 谓词不能容纳空列表

expression IN (value [, ...])

由于 hibernate 按原样传递 native 查询,因此可以预见这会导致问题。

但作为解决方法,您可以按照 this 操作建议:用不可能的值初始化列表

编辑

实际上,这种行为在 hibernate 5.4.10 中已更改。请参阅commit :

SHA-1: ab9ae431858dc6727023d7f03bd6925f99011c62

* HHH-8901 replace "in ()" SQL with "in (null)" in QueryParameterBindingsImpl

对于您的情况,将生成以下 sql:

select * from history h where h.project_id in (null)

任务 HHH-8901 看起来很奇怪描述与这些更改完全无关。

关于spring-boot - 表达式为空会导致 native 查询出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63658116/

相关文章:

spring-boot - w/Gradle将基于Spring的Web应用程序部署到WAS Liberty时超时

java - Hibernate查询缓存并发策略

spring-boot - 如何使用下划线变量解决 Spring Boot findBy 方法

java - 如何使用 findById() 在数据库中搜索字符串而不是 id?

spring-boot - 带有 Tomcat 7 的 Spring Boot JPA

javascript - 使用 Ajax POST 到 REST 服务失败

java - 使用 Spring Boot 和注释配置 ViewResolver 给出 No mapping found for HTTP request with URI error

java - 从 hibernate DAO 实现中抛出有意义的异常

java - 在 @Query JPA Postgresql 中使用 WITH 子句

java - GenericDAO 与 Guice,玩转泛型和参数化类型