Dear users,
I am attempting to map a parent -> child -> grandchild hierarchy, where each of the two relationships is OneToMany.
Grandchild is an inner-most entity:
Code:
@Entity
public class Grandchild implements java.io.Serializable {
@Id @GeneratedValue
Long id;
private String name;
}
Child has a list of grandchildren:
Code:
@Entity
public class Child implements Serializable {
@Id @GeneratedValue
Long id;
@Column(name = "name", length = 100)
private String name;
@OneToMany(fetch=FetchType.EAGER ,cascade=CascadeType.ALL)
@JoinColumn(name="childId")
List<Grandchild> grandchildren;
}
And a parent has a list of children:
Code:
public class Parent implements Serializable {
@Id @GeneratedValue
Long id;
@Column(name = "name", length = 100)
private String name;
@OneToMany(fetch=FetchType.EAGER ,cascade=CascadeType.ALL)
@JoinColumn(name="parentId")
private List<Child> children;
}
I am populating the structure with 1 parent having 2 children, each having 2 grandchildren, and the data base looks correct after persist. However, retrieving it back with
Code:
... em.find(Parent.class, p.getId())
brings back a parent with 4 children, where each of the two children was duplicated (but still correctly contains two of its own grandchildren).
This is likely explained by the hibernate code generated to retrieve the parent, which looks like this:
Code:
select
parent0_.id as id1_2_0_,
parent0_.name as name2_2_0_,
children1_.parentId as parentId3_2_1_,
children1_.id as id1_0_1_,
children1_.id as id1_0_2_,
children1_.name as name2_0_2_,
grandchild2_.childId as childId3_0_3_,
grandchild2_.id as id1_1_3_,
grandchild2_.id as id1_1_4_,
grandchild2_.grandchildName as grandchi2_1_4_
from
public.Parent parent0_
left outer join
public.Child children1_
on parent0_.id=children1_.parentId
left outer join
public.Grandchild grandchild2_
on children1_.id=grandchild2_.childId
where
parent0_.id=?
My expectation was to be able to retrieve the parent -> child -> grandchild hierarchy upon the find method.
I would hugely appreciate a clue as to what is wrong with the annotation setup!