【发布时间】:2021-02-21 02:42:22
【问题描述】:
我有以下带有 where 子句的 JPA 查询:
@Query("SELECT P FROM ParentEntity P \n" +
"INNER JOIN P.childEntities C \n" +
"WHERE C.childId IN (:childIds)")
List<ParentEntity> findByChildIds(@Param("childIds") List<UUID> childIds);
childId 列在表中是 notnull,所有行都有该列的值。
当 childIds 参数有值时,查询工作正常。但是 childIds 是一个可选参数,它可能是一个空列表或 null,在这种情况下我想忽略 where 子句并简单地返回
SELECT P FROM ParentEntity P \n" +
"INNER JOIN P.childEntities C
所以我将查询修改为:
@Query("SELECT P FROM ParentEntity P \n" +
"INNER JOIN P.childEntities C \n" +
"WHERE ((:childIds) IS NULL OR C.childId IN (:childIds))")
List<ParentEntity> findByChildIds(@Param("childIds") List<UUID> childIds);
现在,当 childIds 为空 (= []) 时,此查询返回 0 个结果,因为 (:childIds) IS NULL 为假,C.childId IN (:childIds) 也始终为假。但我想要这种情况下的所有行。
当childIds为null时,则抛出异常:
org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $1
我希望所有行也返回这里,而不是例外。
【问题讨论】:
-
尝试添加
or :childIds = [] -
给出 QuerySyntaxException
-
尝试使用
COALESCE(:childIds, null) is null
标签: sql postgresql jpa spring-data-jpa