JPQL 中如何查询可以为空的集合?

How to query a collection that can be null in JPQL?

假设我有一个这样的实体

class Parent {
    @OneToMany(mappedBy = "par")
    Set<Child> children

    String stuff;
}

class Child {
    @ManyToOne
    @JoinColumn(name="par_id", nullable=false)
    private Parent par;

    String value;
}

我想要这样的查询:

Select DISTINCT par from Parent par LEFT JOIN par.children chi 
WHERE
( par.stuff = :stuff or (:stuff is null))
AND ((chi is not empty) and chi.value = :value))

但是这让我返回 parents 有空的 children。

我需要 select 所有 Parent 有一组非空 children 并且 children 匹配值 = x

您可以尝试使用 inner join 来确保 children 存在:

select distinct par from Parent par join par.children chi where chi.value = :value

您可以使用 exists 运算符:

select distinct par from Parent par 
where exists 
 (select chi 
  from Child chi 
where chi.value = :value and chi.parent = par)