Search code examples
hibernatehqlhibernate-onetomany

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


I have 2 tables : Parent and Child and oneToMany relation between Parent and 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;
    }
}

Now I want to fetch parent with all children whose one of the children is 10 or more years old and parent is married. In other words, Let's say P1 has 2 children, c1 age = 11 and c2 = 8 and p1.marritalStatus is married.
So my query should fetch P1 with c1 and c2.

Right now it's only fetching P1 with c1. No c2. And p1.getChildren() only gives c1.

My HQL looks like:

1st Query which I execute: get parent ID List

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

I get correct parent ID list Pass that parent ID (P1 in this case) list in 2nd query

2nd Query on Parent Table (no joins to child table) "from Parent as p where p.parentID IN (parentIDList)"

Since FetchType is EAGER, I thought hibernate will fetch all children when I fetch parent but doesnt look so.

I tried - join with Child table for 2nd query but it doesn't give desirable result.

My 1st query works fine and I get correct parent list, my problem is not getting all childrent when I run 2nd query. how to resolve that?


Solution

  • I had to clear session. I dont need join 2nd time to pull all children since fetchtype is EAGER.