Hi all!
I encountered a problem with lazy association. Here is my simplified class hierarchy:
Code:
@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 simple structure from db: A->B->C i get the following results:
Code:
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 instance of C is not properly initialized. After changing fetch type from LAZY to EAGER for field c in class B everything works!
I suspect there is is some CGLIB magic, but can't find a clue nether in the specification nor in Google. Could someone explain this?
Thanks for any help!!!