3

I have three Entities 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 an eagerly loaded reference of B in A and between B and C is a lazily loaded bidirectional relation.

My problem: When fetching an instance of A from the DB, an instance of C is fetched as well by Hibernate.

I discovered 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"));
}

That last Assert fails.

Luckily there was no problem getting rid of the bidirectional relation, but I would like to know the source of the problem. Is it the intended behaviour of Hibernate to eagerly load all references of an entity, that is eagerly loaded?

Gimby
  • 4,565
  • 2
  • 32
  • 44
Thomas
  • 575
  • 10
  • 28

1 Answers1

1

It seems there is some problem with OneToOne Lazy loading. There is post in Hibernate forums explaining why and giving some advices( https://forum.hibernate.org/viewtopic.php?f=1&t=1001116 ). I would suggest to try search before you ask. Also I think this was already asked here and got also really good answer: Try this one: Making a OneToOne-relation lazy

Community
  • 1
  • 1
ap0calypt1c
  • 471
  • 4
  • 10
  • Thanks for the answer. Obviously I couldn't find it myself, because I thought it only mattered for eager loaded entities, not every OneToOne-Relationship. – Thomas Jul 31 '15 at 09:15