Files
hibernate-demo/src/test/java/com/ankurm/hibernatedemo/proxy/OpenInViewAndLazyLoadNoTransTest.java
T

66 lines
2.9 KiB
Java
Executable File

package com.ankurm.hibernatedemo.proxy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.hibernate.LazyInitializationException;
import org.hibernate.Session;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
/**
* Backs docs/11-proxies-and-lazy-initialization.md, chapter "hibernate.enable_lazy_load_no_trans: does it still exist?".
*
* <p>{@code org.hibernate.cfg.TransactionSettings.ENABLE_LAZY_LOAD_NO_TRANS} still resolves to
* the constant string {@code hibernate.enable_lazy_load_no_trans} in Hibernate 7.4.5.Final --
* confirmed by {@code javap} on the jar (see docs/output/proxy-settings-javap.txt). It is NOT
* removed. It IS annotated {@code @org.hibernate.cfg.Unsafe}, a marker interface with no members
* that Hibernate's own codebase uses to flag settings the team does not want you reaching for.
* This test proves the setting still functionally does something in 7.4.5: with it enabled, a
* lazy proxy can be touched after its own originating transaction/session has ended, because
* Hibernate opens a temporary session behind the scenes to service exactly that one lazy load.
*/
@SpringBootTest
@TestPropertySource(properties = {
"spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true"
})
class OpenInViewAndLazyLoadNoTransTest {
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
@Autowired
private EntityManagerFactory emf;
@Test
void withEnableLazyLoadNoTrans_toOneProxyInitializesAfterSessionCloses_viaTemporarySession() {
EntityManager seedEm = emf.createEntityManager();
seedEm.getTransaction().begin();
ProxyPublisher publisher = new ProxyPublisher("No-Trans Press");
seedEm.persist(publisher);
ProxyBook book = new ProxyBook("No-Trans Book", publisher);
seedEm.persist(book);
seedEm.getTransaction().commit();
Long id = book.getId();
seedEm.close();
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Session session = em.unwrap(Session.class);
ProxyBook proxy = session.getReference(ProxyBook.class, id);
em.getTransaction().commit();
em.close();
// No exception here: with enable_lazy_load_no_trans=true, Hibernate 7.4.5 opens a
// temporary session to service this access instead of throwing.
String title = proxy.getTitle();
DEMO.info("enable_lazy_load_no_trans=true: proxy.getTitle() after close returned '{}' with no exception", title);
assertThat(title).isEqualTo("No-Trans Book");
}
}