Hibernate LAZY selection does not initialize instance

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 !!!

+4
source share
2 answers

Fixed. My question was wrong. I'm sorry. There was a final modifier for the getters and setters of my entitiy classes. It breaks associations with one meaning, like many-to-one. Suppose I skipped some warnings in sleep logs ... I think it would be better to throw a sleep exception for this case.

0
source

If you want to understand lazy loading, see this answer ; he defines her very well.

+1
source

All Articles