我使用Hibernate
和JpaRepository
处理我的数据库操作。
我有这个查询(为了简化,因为原始查询相当大):
@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/