【发布时间】:2021-02-24 00:51:19
【问题描述】:
我有一个 N-N 产品类别模型,并且我创建了一个 Spring Data JPA @Query 来检索给定类别的产品(或者如果类别为空,则为所有产品):
@Query("SELECT DISTINCT obj FROM Product obj INNER JOIN obj.categories cats WHERE "
+ "(:category IS NULL OR :category IN cats)")
Page<Product> find(Category category, Pageable pageable);
它在 H2 数据库中完美运行。但是,在 Postgres 12 中进行测试时,如果给出了 null 类别,则会出现以下错误:
org.postgresql.util.PSQLException: ERROR: operator does not exist: bytea = bigint
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Coalesce 曾因 Instant 类型参数的类似问题而救过我一次,但这次它没有解决实体参数的问题:
+ "(COALESCE(:category, NULL) IS NULL OR :category IN cats)")
以防万一,我只测试了 NULL,它不会为 null 和 not null 类别抛出任何错误:
+ "(:category IS NULL")
我也只测试了 IN 子句,并且在给出空类别时得到相同的“运算符不存在”错误:
+ "(:category IN cats)")
测试表明,显然,OR 运算符之前的:category IS NULL 条件不会阻止对:category IN cats 进行评估。我该如何解决这个问题?
【问题讨论】:
-
嘿 Nelio,你找到解决方案了吗?我也面临同样的问题
标签: spring postgresql spring-boot spring-data-jpa