Search code examples
javahibernatehibernate-criteria

Fetching child, grandchild using a parent attribute in hibernate


I have a hibernate query.

Parent -> Child -> GrandChild

I have a Parent class which has a one to many relation to Child class and a GrandChild class which has one to many. I need to fetch all the corresponding child and grand child entities in an optimised way.

  public class Parent  {
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
  private List<Child> children = new ArrayList<>(); 

}

public class Child {
 @ManyToOne(fetch = FetchType.LAZY)
  private Parent parent;

  @OneToMany(
      mappedBy = "child",
      cascade = {CascadeType.ALL},
      orphanRemoval = true)
  private List<GrandChild> grandChild = new ArrayList<>();
}

public class GrandChild {
  @ManyToOne
  private Child child;
   
}

I already tried using join and then left join fetch but it doesn't work on all three levels. If the Grandchild has no values it works, otherwise not. I don't want to make fetch type eager as it will have performance impact.


Solution

  • I solved it. The direct query given below worked. But we need to add @JsonIgnore to the getters and setters of the parent(upper level) references in the child classes so as to not go in a recursive loop.

    var query =
            em.createQuery(
                "select parent from Parent parent left join fetch parent.children "
                    + "as children   where  parent.name=:name",
                Parent.class);
    

    Hope it helps.