Reputation: 61
I encountered a problem with lazy association two days ago and still haven't found an explanation of such a 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 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 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!!!
Upvotes: 4
Views: 1339
Reputation: 61
Fixed. My question was not correct. Sorry. There was final modifier for getters and setters of my entitiy classes. It breaks single value associations like many-to-one. Suppose I've missed some warnings in hibernate logs... I think it would be better to throw an exception by hibernate for this case.
Upvotes: 0
Reputation: 14373
In case you would like to understand lazy loading see this answer; it defines it pretty well.
Upvotes: 1