Hibernate willingly loads a lazy link
I have three objects A, B and C.
@Entity
public class A {
@Id
private long id;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ID", insertable = false, updatable = false)
public B b;
}
@Entity
public class B {
@Id
private long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID", insertable = false, updatable = false)
public C c;
}
@Entity
public class C {
@Id
private long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID", insertable = false, updatable = false)
public B b;
}
So there is a loaded link B in A, and there is a lazy loaded bi-directional relationship between B and C.
My problem: When retrieving instance A from DB, instance C is also fetched using Hibernate.
I found it in a heap dump due to a memory leak and tested it programmatically:
@Test
public void eagerAndLazyLoading() {
A a = dao.getA(1L);
Assert.assertNotNull(a);
PersistenceUnitUtil puu = emf.getPersistenceUnitUtil();
Assert.assertTrue(puu.isLoaded(a));
Assert.assertTrue(puu.isLoaded(a, "b"));
Assert.assertFalse(puu.isLoaded(a.b, "c"));
}
This last Assert fails.
Fortunately, there was no problem getting rid of the bidirectional relationship, but I would like to know the source of the problem. Is it the intended behavior of Hibernate to eagerly load all references to an object that is eagerly loaded?
source to share
There seems to be some problem downloading OneToOne Lazy. There is a post in the Hibernate forums explaining why and providing some advice ( https://forum.hibernate.org/viewtopic.php?f=1&t=1001116 ). I would suggest giving it a try before asking. Also I think this has already been asked here and got a very good answer as well: try this: Create a OneToOne lazy relationship
source to share