I’m attempting to use hibernate-test-case-templates to ask a question about lazy loading behavior for entities. In the real application I have a Parent / Child entity relationship. I think I should be able to call child.parent.getId() and hibernate will not load the parent because that id is present as a foreign key on the child.
I’m getting a third behavior from this test case which is neither what I’m seeing in my app, nor what I expect to see.
@Test
void hhh123Test() throws Exception {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
Parent parent = new Parent();
entityManager.persist(parent);
Child child = new Child().setParent(parent);
entityManager.persist(child);
entityManager.getTransaction().commit();
entityManager.close();
// LOAD ------------------------------------------------------------------
EntityManager entityManager2 = entityManagerFactory.createEntityManager();
entityManager2.getTransaction().begin();
Child loaded = entityManager2.find(Child.class, child.getId());
System.out.println();
Parent loadedParent = loaded.parent;
long a = loadedParent.getId();
entityManager2.getTransaction().commit();
entityManager2.close();
}
In the test case, when I load the Child entity, it also loads the parent before loaded.parent is accessed:
Hibernate:
select
c1_0.id,
c1_0.parent_id,
c1_0.tenant_id
from
Child c1_0
where
c1_0.id=?
and c1_0.tenant_id = ?
Hibernate:
select
p1_0.id,
p1_0.tenant_id
from
Parent p1_0
where
p1_0.id=?
and p1_0.tenant_id = ?
Any ideas what’s going on here? Once I have this working as expected, I want to demonstrate that hibernate is loading the full Parent row to get the id when as far as I can tell from the documentation, it should not have to do that. Thanks!