休眠提取 parent 和所有 children 如果 children 中的任何一个满足条件

Hibernate fetch parent and all children if any of children meet criteria

我有 2 个 table:Parent 和 Child 以及 Parent 和 Child

之间的一对多关系
@Entity
@Table(name="PARENT")
public class Parent {
   int parentID;
   String marritalStatus;
   List<Child> children;

   //getters and setters

   @OneToMany(mappedBy = "parent", cascade=CascadeType.ALL, orphanRemoval=true, fetch = FetchType.EAGER)
   public List<Child> getChildren() {
    return children;
}
}

@Entity
@Table(name="CHILD")
public class Child{
   private Parent parent;           //FK
   private int age; 
   private int childID;

   @ManyToOne
   @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", nullable=false)
    public Parent getParent() {
      return parent;
    }

    public void setParent(Parent parent) {
         this.parent = parent;
    }
}

现在我想获取 parent 和所有 children 中的一个 children 已满 10 岁并且 parent 已婚。 换句话说, 假设 P1 有 2 children,c1 age = 11 和 c2 = 8 并且 p1.marritalStatus 已婚。
所以我的查询应该使用 c1 和 c2 获取 P1。

现在只能用c1获取P1。没有c2。 p1.getChildren() 只给出 c1.

我的 HQL 看起来像:

我执行的第一个查询:获取 parent ID 列表

parentIDList = select p.parentID from Parent as p LEFT JOIN fetch p.children as c where c.age > 10 and p.marritalStatus = 'married'"

我得到正确的parent ID列表 在第二个查询中传递 parent ID(在本例中为 P1)列表

对 Parent Table 的第二次查询(没有连接到 child table) "from Parent as p where p.parentID IN (parentIDList)"

由于 FetchType 是 EAGER,我认为当我获取 parent 时 hibernate 会获取所有 children 但看起来并非如此。

我试过 - 加入 Child table 进行第二次查询,但没有给出理想的结果。

我的第一个查询工作正常,我得到了正确的 parent 列表,我的问题是当我 运行 第二个查询时没有得到所有 childrent。如何解决?

试试这个,让 parent 结婚:

select c.parent.parentID from Children c where c.age > 10 and c.parent.marritalStatus = 'married'

说明:

Children 知道他们的 parent,因此您可以访问 parent 的字段。

首先,当您在 Hibernate 中触发任何 HQL 查询时,它总是会忽略您的实体级提取模式 (fetch = FetchType.EAGER)。要获得所有 child 和 parent,您需要使用显式加入。所以请写下一个普通的 hql 查询,它使用 join 来获取你的 child table 记录。

尝试下面给定的查询它对我有用....

select p From Parent as p JOIN FETCH p.children as c where c.age >= 10

我必须清除会话。我不需要第二次加入来拉取所有 children 因为 fetchtype 是 EAGER.