【问题标题】:How to query a collection that can be null in JPQL?如何在 JPQL 中查询可以为空的集合?
【发布时间】:2020-06-11 23:58:44
【问题描述】:

假设我有这样的实体

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))

但这让我回到了有空孩子的父母。

我需要选择所有具有一组非空子项和匹配值 = x 的子项的所有父项

【问题讨论】:

  • 如果您提供映射将更容易理解和帮助。你是故意省略的吗?
  • 我编辑了这个问题,这就是你所说的映射的意思吗?
  • 我的意思是对象关系映射:JPA/hibernate 注释或 hibernate xml 配置文件。
  • 添加注释

标签: spring jpa jpql


【解决方案1】:

您可以尝试使用inner join 来确保孩子的存在:

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)

【讨论】:

    猜你喜欢
    • 2014-05-04
    • 2017-04-12
    • 2021-09-10
    • 2012-10-31
    • 2017-12-23
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    相关资源
    最近更新 更多