I ran into the problem of lazy association two days ago and still have not found an explanation for this behavior. Here is my simplified class hierarchy:
@Entity @Table(name="A") public class A { @Id @GeneratedValue @Column(name="ID") private int id; @OneToMany(mappedBy="a", fetch=FetchType.LAZY, cascade=CascadeType.ALL) private Set<B> listB = new HashSet<B>(); } @Entity @Table(name="B") public class B { @Id @GeneratedValue @Column(name="ID") private int id; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="A_ID") private A a; @ManyToOne(fetch=FetchType.LAZY) // ERROR! // @ManyToOne(fetch=FetchType.EAGER) // OK @JoinColumn(name="C_ID") private C c; } @Entity @Table(name="C") public class C { @Id @GeneratedValue @Column(name="ID") private int id; }
When I try to read a simple structure from db: A-> B-> C, I get the following results:
System.out.println(a.getId()); // 1 for (B b : a.getListB()) { System.out.println(b.getId()); // 1 C c = b.getC(); System.out.println(c.getId()); // 0 !!! }
As you can see, the C instance is not properly initialized. After changing the sample type from LAZY to EAGER for field c in class B, everything works!
I suspect there is some kind of CGLIB magic, but I canβt find the key in the specs and on Google. Can someone explain this?
Thanks for any help !!!
source share