我正在使用 Hibernate 从 Postgresql DB 获取数据,但在尝试将 EMPTY 或 NULL 作为 Long 值列表传递给查询时总是出现此错误:
@Repository
public interface ProductRepository extends JpaRepository<Category, Long> {
@Query(nativeQuery = true,
value = "SELECT * FROM Products p " +
"WHERE (COALESCE(:#{#param.colors}) IS NULL OR p.color IN (:#{#param.colors}))")
List<Product> findFiltered(@Param("param") ProductFilterParams params);
}
(注意:由于请求复杂,我使用原生查询)
ProductFilterParams 看起来像:
@Data
public class ProductFilterParams {
private List<Long> colors;
...other product filters...
}
所以我的想法是按颜色过滤产品(效果很好)或显示所有产品,如果没有颜色过滤器(这里我得到这个错误)。
当我将 null 作为颜色日志传递时:
binding parameter [1] as [LONGVARCHAR] - [null]
ERROR: operator does not exist: bigint = character varying
或者当我尝试传递空列表时:
*** NO BINDING LOG AT ALL ***
ERROR: syntax error at or near ")"
我不知道为什么会出现这个错误以及如何解决它。 我尝试了一些来自 web/stackoverflow 的谷歌搜索答案,但所有这些都是针对 HQL 的,无法针对 native 查询修复它。
最佳答案
实际上,hibernate 文档 says :
IN
predicates performs a check that a particular value is in a list of values. Its syntax is:
in_expression ::= single_valued_expression [NOT] IN single_valued_list
single_valued_list ::= constructor_expression | (subquery) | collection_valued_input_parameter
constructor_expression ::= (expression[, expression]*)
The list of values can come from a number of different sources. In the
constructor_expression
andcollection_valued_input_parameter
, the list of values must not be empty; it must contain at least one value.
但是,正如所解释的那样here它在 hibernate 5.4.10 中被更改。但是当您使用 hibernate 5.3.7.final 时,您应该在查询之外移动检查集合是否为空。
顺便说一句,使用COALESCE是没有意义的具有一个参数的函数。
关于java - 错误 : operator does not exist: bigint = character varying for empty list of long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65932668/