I am using Hibernate 4.3.6.Final
I have 3 classes :
- Parent
- Child
- Grandchild
As you can imagine, a Parent has many Children, and a Child has many Grandchildren.
class Parent {
@OneToMany(orphanRemoval = true)
@OrderColumn(name = "list_order")
@JoinColumn(name = "parent_id", nullable = false)
@Cascade(value = CascadeType.ALL)
private List<Child> children = new ArrayList<>();
}
class Child {
@ManyToOne(optional = false)
@JoinColumn(name = "parent_id", insertable=false, updatable=false, nullable = false,
foreignKey = @ForeignKey(name = "fk_child_parent_id"))
private Parent parent;
@OneToMany(orphanRemoval = true, fetch = FetchType.EAGER)
@OrderColumn(name = "list_order")
@JoinColumn(name = "child_id", nullable = false)
@Cascade(value = CascadeType.ALL)
private List<Grandchild> grandchildren = new ArrayList<>();
}
class Grandchild {
@ManyToOne(optional = false)
@JoinColumn(name = "child_id", insertable=false, updatable=false, nullable = false,
foreignKey = @ForeignKey(name = "fk_grandchild_child_id"))
private Child child;
}
I want to LAZY load Children but EAGER load Grandchildren when loading Children.
Which means that :
- When I access Parent, I want Hibernate to fetch only Parent
- But if I call parent.getChildren(), I want Hibernate to fetch all children AND grandchildren
I've set EAGER on Child<->Granchild association, but it has no effect : when I call parent.getChildren(), only the children are fetched, not the grandchildren.
Thanks for your help !
UPDATE @Zeus, in my database :
- Table Parent has "id"
- Table Child has "id", "parent_id" (foreign key of parent) and "list_order" (used by Hibernate to order the list of children)
- Table Grandchild has "id", "child_id" (foreign key of child) and "list_order"