Add Hibernate 7 batches 2-6, batch 7, and batch 8: mapping styles, JPA annotations, natural IDs, @Immutable, stored procedures, in-memory test databases, JNDI mocking, proxies, associations, temporal mapping, named queries, HQL, Criteria API, EntityManager bootstrapping, Ehcache 3 L2 cache configuration, HikariCP connection pooling, Hibernate Validator CDI integration, aggregate functions, sorting, pagination, interceptors, and Hibernate Search 8 (Hibernate 7.4.5.Final + Spring Boot 4.1.1 + JDK 25)

This commit is contained in:
2026-09-20 06:06:42 +00:00
committed by Claude
commit 8568c0ce6c
330 changed files with 23668 additions and 0 deletions
@@ -0,0 +1,131 @@
package com.ankurm.hibernatedemo.proxy;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityGraph;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import java.util.Map;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
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;
/**
* Backs docs/11-proxies-and-lazy-initialization.md, chapter "fetchgraph vs loadgraph, actually demonstrated".
*
* <p>{@link ProxyBook} has two associations: {@code publisher} (default fetch type, EAGER) and
* {@code reviews} (explicit LAZY). The named graph {@code Book.reviews-only} names only
* {@code reviews}. The two JPA hint keys treat the association NOT named in the graph
* differently:
*
* <ul>
* <li>{@code jakarta.persistence.loadgraph} -- attributes not in the graph keep their
* mapped fetch type. {@code publisher} stays EAGER and gets joined anyway.</li>
* <li>{@code jakarta.persistence.fetchgraph} -- the graph IS the complete fetch plan.
* Any attribute not in it is forced to LAZY, so {@code publisher} does NOT get joined,
* regardless of its mapped EAGER fetch type.</li>
* </ul>
*/
@SpringBootTest
class EntityGraphFetchTest {
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
@Autowired
private EntityManagerFactory emf;
private Statistics stats() {
return emf.unwrap(SessionFactory.class).getStatistics();
}
private Long seedBookWithReviewAndPublisher() {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
ProxyPublisher publisher = new ProxyPublisher("Graph Press");
em.persist(publisher);
ProxyBook book = new ProxyBook("Graph Book", publisher);
em.persist(book);
ProxyReview review = new ProxyReview("Nice graph", book);
em.persist(review);
em.getTransaction().commit();
Long id = book.getId();
em.close();
return id;
}
@Test
void loadgraph_joinsNamedAttributeAndKeepsMappedEagerAttributeJoinedToo() {
Long id = seedBookWithReviewAndPublisher();
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
EntityGraph<?> graph = em.getEntityGraph("Book.reviews-only");
stats().clear();
ProxyBook book = em.find(ProxyBook.class, id, Map.of("jakarta.persistence.loadgraph", graph));
// One SELECT total: publisher (mapped EAGER, loadgraph does not touch it) and
// reviews (named in the graph) are both fetched without a second round-trip.
assertThat(stats().getPrepareStatementCount())
.as("loadgraph must fetch the named attribute AND keep the mapped-EAGER one, in one query")
.isEqualTo(1);
assertThat(Hibernate.isInitialized(book.getPublisher()))
.as("loadgraph does not demote attributes outside the graph -- publisher is still EAGER")
.isTrue();
assertThat(Hibernate.isInitialized(book.getReviews())).isTrue();
em.getTransaction().commit();
em.close();
}
@Test
void fetchgraph_joinsOnlyNamedAttributeAndForcesMappedEagerAttributeToLazy() {
Long id = seedBookWithReviewAndPublisher();
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
EntityGraph<?> graph = em.getEntityGraph("Book.reviews-only");
stats().clear();
ProxyBook book = em.find(ProxyBook.class, id, Map.of("jakarta.persistence.fetchgraph", graph));
assertThat(stats().getPrepareStatementCount())
.as("fetchgraph's single SELECT still includes the join for the named attribute")
.isEqualTo(1);
assertThat(Hibernate.isInitialized(book.getReviews())).isTrue();
assertThat(Hibernate.isInitialized(book.getPublisher()))
.as("fetchgraph treats the graph as the WHOLE fetch plan -- publisher is forced back to LAZY "
+ "even though its mapping says EAGER")
.isFalse();
DEMO.info("fetchgraph: book.getPublisher() runtime class = {}", book.getPublisher().getClass().getName());
em.getTransaction().commit();
em.close();
}
@Test
void noGraphAtAll_defaultFindStillJoinsTheMappedEagerAssociationButLeavesLazyCollectionAlone() {
Long id = seedBookWithReviewAndPublisher();
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
stats().clear();
ProxyBook book = em.find(ProxyBook.class, id);
assertThat(stats().getPrepareStatementCount()).isEqualTo(1);
assertThat(Hibernate.isInitialized(book.getPublisher()))
.as("plain find() honours the mapping: publisher is EAGER by default")
.isTrue();
assertThat(Hibernate.isInitialized(book.getReviews()))
.as("plain find() honours the mapping: reviews is LAZY by default")
.isFalse();
em.getTransaction().commit();
em.close();
}
}
@@ -0,0 +1,147 @@
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.Hibernate;
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;
/**
* Backs docs/11-proxies-and-lazy-initialization.md (post 4870 rewrite), chapter "The exception, verbatim".
*
* <p>Reproduces {@code org.hibernate.LazyInitializationException} for real against Hibernate
* 7.4.5.Final and captures the exact message and package, instead of restating the docs.
*/
@SpringBootTest
class LazyInitializationTest {
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
@Autowired
private EntityManagerFactory emf;
private Long seedBookWithReview(String title) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
ProxyPublisher publisher = new ProxyPublisher("O'Reilly");
em.persist(publisher);
ProxyBook book = new ProxyBook(title, publisher);
em.persist(book);
ProxyReview review = new ProxyReview("Great book", book);
em.persist(review);
book.getReviews().add(review);
em.getTransaction().commit();
Long id = book.getId();
em.close();
return id;
}
@Test
void accessingLazyCollectionAfterSessionClose_throwsLazyInitializationException() {
Long id = seedBookWithReview("Effective Hibernate");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
ProxyBook book = em.find(ProxyBook.class, id);
assertThat(Hibernate.isInitialized(book.getReviews()))
.as("a freshly-found entity's LAZY collection must not be initialized yet")
.isFalse();
em.getTransaction().commit();
em.close();
// The persistence context is gone. Touching the collection now must fail, not
// silently open a new connection.
LazyInitializationException ex = assertThrows(
LazyInitializationException.class,
() -> book.getReviews().size());
DEMO.info("verbatim exception class: {}", ex.getClass().getName());
DEMO.info("verbatim exception message: {}", ex.getMessage());
assertThat(ex.getClass().getName()).isEqualTo("org.hibernate.LazyInitializationException");
// NOTE: this is the COLLECTION-flavoured message. It is NOT "could not initialize
// proxy - no Session" -- that wording belongs to a to-one association proxy, exercised
// separately below. Blog posts (including the one this test corrects) routinely quote
// the proxy message for a collection access; they are two different message templates.
assertThat(ex.getMessage()).contains("Cannot lazily initialize collection of role");
assertThat(ex.getMessage()).contains("(no session)");
}
@Test
void accessingToOneProxyAfterSessionClose_throwsTheOtherLazyInitializationMessage() {
Long id = seedBookWithReview("To-One Proxy Message");
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();
LazyInitializationException ex = assertThrows(LazyInitializationException.class, proxy::getTitle);
DEMO.info("to-one proxy verbatim message: {}", ex.getMessage());
// Verbatim in 7.4.5.Final: "Could not initialize proxy [com.ankurm.hibernatedemo.proxy.ProxyBook#4] - no session"
// Capital "Could", lower-case "no session" -- NOT the commonly-quoted
// "could not initialize proxy - no Session" (capital Session). Both this article's
// sources and long-standing folklore get the capitalization backwards.
assertThat(ex.getMessage()).contains("Could not initialize proxy");
assertThat(ex.getMessage()).contains("no session");
}
@Test
void hibernateInitialize_forcesLoadInsideTransaction_thenIsInitializedFlips() {
Long id = seedBookWithReview("Initialize Me");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
ProxyBook book = em.find(ProxyBook.class, id);
assertThat(Hibernate.isInitialized(book.getReviews())).isFalse();
Hibernate.initialize(book.getReviews());
assertThat(Hibernate.isInitialized(book.getReviews())).isTrue();
em.getTransaction().commit();
em.close();
// Now that it was initialized while the session was open, reading it after close
// works -- no exception, because there is nothing left to lazily fetch.
assertThat(book.getReviews()).hasSize(1);
assertThat(book.getReviews().get(0).getComment()).isEqualTo("Great book");
}
@Test
void hibernateUnproxy_onManyToOneReference_returnsRealInstance_notTheProxySubclass() {
Long id = seedBookWithReview("Unproxy Me");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Session session = em.unwrap(Session.class);
ProxyBook proxy = session.getReference(ProxyBook.class, id);
DEMO.info("getReference() proxy class: {}", proxy.getClass().getName());
assertThat(proxy.getClass()).isNotEqualTo(ProxyBook.class);
assertThat(Hibernate.isInitialized(proxy)).isFalse();
Object unproxied = Hibernate.unproxy(proxy);
DEMO.info("Hibernate.unproxy(proxy) class: {}", unproxied.getClass().getName());
assertThat(unproxied.getClass()).isEqualTo(ProxyBook.class);
assertThat(Hibernate.isInitialized(proxy))
.as("Hibernate.unproxy() initializes the proxy as a side effect")
.isTrue();
// Two-arg overload: Hibernate.unproxy(T, Class<T>)
ProxyBook typed = Hibernate.unproxy(proxy, ProxyBook.class);
assertThat(typed.getClass()).isEqualTo(ProxyBook.class);
em.getTransaction().commit();
em.close();
}
}
@@ -0,0 +1,65 @@
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");
}
}
@@ -0,0 +1,27 @@
package com.ankurm.hibernatedemo.proxy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* Test-only support for docs/11-proxies-and-lazy-initialization.md's OSIV chapter (OsivMaskingTest). Returns the
* managed entity directly (not a DTO) ON PURPOSE -- Jackson's serialization of
* {@code getReviews()} on the response-writing thread is the exact moment open-in-view either
* saves you (session still bound, proxy initializes) or doesn't (session long closed,
* LazyInitializationException).
*/
@RestController
public class OsivBookController {
private final OsivBookService service;
public OsivBookController(OsivBookService service) {
this.service = service;
}
@GetMapping("/osiv/books/{id}")
public ProxyBook getBook(@PathVariable Long id) {
return service.findBook(id);
}
}
@@ -0,0 +1,27 @@
package com.ankurm.hibernatedemo.proxy;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Test-only support for docs/11-proxies-and-lazy-initialization.md's OSIV chapter (OsivMaskingTest). Deliberately
* uses the container-managed, request/transaction-synchronized {@link EntityManager} (via
* {@code @PersistenceContext}), not a manually created one -- open-in-view only has anything
* to bind to the request thread when the shared, Spring-managed EntityManager is the one in
* play.
*/
@Service
public class OsivBookService {
@PersistenceContext
private EntityManager entityManager;
@Transactional(readOnly = true)
public ProxyBook findBook(Long id) {
// Deliberately does NOT touch getReviews() here -- whether that succeeds later, during
// JSON serialization in the web layer, is exactly the thing under test.
return entityManager.find(ProxyBook.class, id);
}
}
@@ -0,0 +1,89 @@
package com.ankurm.hibernatedemo.proxy;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.test.web.server.LocalServerPort;
/**
* Backs docs/11-proxies-and-lazy-initialization.md, chapter "OSIV: the default, its warning, and what it actually
* masks". Deliberately does NOT set {@code spring.jpa.open-in-view} -- Boot's own default
* (true) is what is under test here, including the startup warning Boot prints because you
* didn't set it explicitly.
*
* <p>Needs a real servlet request (see {@link OsivBookController}, {@link OsivBookService}):
* open-in-view is implemented by {@code OpenEntityManagerInViewInterceptor}, which only exists
* for actual web applications -- the base app here runs with
* {@code spring.main.web-application-type=none}, so this test overrides that to {@code servlet}
* and spins up a random-port embedded Tomcat just for itself.
*/
@ExtendWith(OutputCaptureExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
// A dedicated config file that has NO spring.jpa.open-in-view key at all -- the shared
// src/main/resources/application.yml sets it to false explicitly, which would hide
// both the warning and the masking behaviour under test here.
"spring.config.name=osiv-default-test"
})
class OsivDefaultWarningTest {
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
@Autowired
private EntityManagerFactory emf;
@LocalServerPort
private int port;
private Long seedBookWithReview() {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
ProxyPublisher publisher = new ProxyPublisher("OSIV Default Press");
em.persist(publisher);
ProxyBook book = new ProxyBook("OSIV Default Book", publisher);
em.persist(book);
ProxyReview review = new ProxyReview("Rendered fine", book);
em.persist(review);
em.getTransaction().commit();
Long id = book.getId();
em.close();
return id;
}
@Test
void defaultOpenInView_printsStartupWarning_andMasksLazyLoadingDuringSerialization(CapturedOutput output) throws Exception {
DEMO.info("checked at context-startup time: {}", output.toString().contains("open-in-view")
? "the OSIV warning line is present in the captured log"
: "NOT FOUND");
assertThat(output.toString())
.as("Boot must print its open-in-view default warning verbatim when the property is left unset")
.contains("spring.jpa.open-in-view is enabled by default");
Long id = seedBookWithReview();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(
HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/osiv/books/" + id)).GET().build(),
HttpResponse.BodyHandlers.ofString());
DEMO.info("default OSIV (true): GET /osiv/books/{} -> status {}, body {}", id, response.statusCode(), response.body());
// With OSIV on, the session/EntityManager is still bound to the request thread while
// Jackson serializes the response, so getReviews() initializes successfully instead of
// throwing -- the exception is masked, not fixed.
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.body()).contains("Rendered fine");
}
}
@@ -0,0 +1,95 @@
package com.ankurm.hibernatedemo.proxy;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.test.web.server.LocalServerPort;
/**
* Backs docs/11-proxies-and-lazy-initialization.md, chapter "OSIV: the default, its warning, and what it actually
* masks" -- the "off" half of {@link OsivDefaultWarningTest}. Same controller, same service,
* same entity graph; only {@code spring.jpa.open-in-view} changes: the base
* src/main/resources/application.yml already sets it to {@code false} explicitly, which this
* test relies on and additionally restates for clarity.
*
* <p>The exception surfaces server-side (visible in the application log, asserted here via
* {@link CapturedOutput}) even though the HTTP error body Boot's default
* {@code BasicErrorController} returns is a bare
* {@code {"timestamp":...,"status":500,"error":"Internal Server Error","path":...}} --
* {@code server.error.include-message=always} does not surface it in the JSON body for this
* failure mode, because the failure happens inside the {@code HttpMessageConverter} while
* writing the response, which Boot reports as a generic 500 rather than routing the original
* exception's message into the error attributes map. That gap is itself worth a line in the
* article: don't rely on the HTTP response body to tell you WHY a 500 happened here -- check
* the log.
*/
@ExtendWith(OutputCaptureExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
"spring.main.web-application-type=servlet",
"spring.jpa.open-in-view=false"
})
class OsivDisabledExceptionTest {
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
@Autowired
private EntityManagerFactory emf;
@LocalServerPort
private int port;
private Long seedBookWithReview() {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
ProxyPublisher publisher = new ProxyPublisher("OSIV Disabled Press");
em.persist(publisher);
ProxyBook book = new ProxyBook("OSIV Disabled Book", publisher);
em.persist(book);
ProxyReview review = new ProxyReview("Never rendered", book);
em.persist(review);
em.getTransaction().commit();
Long id = book.getId();
em.close();
return id;
}
@Test
void openInViewFalse_theSameControllerNowThrowsDuringSerialization(CapturedOutput output) throws Exception {
Long id = seedBookWithReview();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(
HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/osiv/books/" + id)).GET().build(),
HttpResponse.BodyHandlers.ofString());
DEMO.info("open-in-view=false: GET /osiv/books/{} -> status {}, body {}", id, response.statusCode(), response.body());
assertThat(response.statusCode())
.as("with OSIV off, the same request that worked in OsivDefaultWarningTest now fails")
.isEqualTo(500);
// Spring logs this as "Resolved [HttpMessageNotWritableException: Could not write
// JSON: Cannot lazily initialize collection of role '...' (no session)]" -- the
// OUTER exception is HttpMessageNotWritableException (thrown by the Jackson message
// converter while writing the response body); LazyInitializationException's own
// MESSAGE text is nested inside it, but the log line does not print
// LazyInitializationException's class name. Assert on the message text that is
// actually, verifiably there.
assertThat(output.toString())
.as("the real cause is visible server-side even though the HTTP error body is generic")
.contains("HttpMessageNotWritableException")
.contains("Cannot lazily initialize collection of role 'com.ankurm.hibernatedemo.proxy.ProxyBook.reviews'")
.contains("(no session)");
}
}
@@ -0,0 +1,101 @@
package com.ankurm.hibernatedemo.proxy;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Hibernate;
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;
/**
* Backs docs/11-proxies-and-lazy-initialization.md, chapter "What a proxy actually is".
*
* <p>{@code getReference()} does not return a {@code ProxyBook} instance -- it returns a
* ByteBuddy-generated subclass. {@code instanceof} sees through it; a naive
* {@code getClass() == SomeEntity.class} check, or the default {@code Object.equals()}/
* {@code hashCode()} pair, does not.
*/
@SpringBootTest
class ProxyIdentityTest {
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
@Autowired
private EntityManagerFactory emf;
private Long seedPublisher(String name) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
ProxyPublisher p = new ProxyPublisher(name);
em.persist(p);
em.getTransaction().commit();
Long id = p.getId();
em.close();
return id;
}
@Test
void getReference_returnsAByteBuddyGeneratedSubclass_notThePlainEntityClass() {
Long id = seedPublisher("Identity Press");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Session session = em.unwrap(Session.class);
ProxyPublisher proxy = session.getReference(ProxyPublisher.class, id);
String className = proxy.getClass().getName();
DEMO.info("getReference() runtime class: {}", className);
// Hibernate 7 generates the proxy as a NESTED class of the entity itself, named
// "$HibernateProxy" -- not a package-level class, and not the Javassist-era naming
// scheme (EntityName_$$_javassist_N) that a lot of still-circulating blog posts show.
assertThat(className).isEqualTo(ProxyPublisher.class.getName() + "$HibernateProxy");
assertThat(className).isNotEqualTo(ProxyPublisher.class.getName());
assertThat(proxy).isInstanceOf(ProxyPublisher.class);
assertThat(proxy.getClass()).isNotEqualTo(ProxyPublisher.class);
assertThat(Hibernate.getClass(proxy))
.as("Hibernate.getClass() sees through the proxy to report the real entity class")
.isEqualTo(ProxyPublisher.class);
em.getTransaction().commit();
em.close();
}
@Test
void naiveEqualsAndHashSet_cannotRecognizeProxyAndRealInstanceAsTheSameRow() {
Long id = seedPublisher("Naive Equals Press");
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();
ProxyPublisher real = em1.unwrap(Session.class).get(ProxyPublisher.class, id);
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
ProxyPublisher proxy = em2.unwrap(Session.class).getReference(ProxyPublisher.class, id);
// ProxyPublisher does not override equals()/hashCode() -- default Object identity.
assertThat(real.getClass()).isNotEqualTo(proxy.getClass());
assertThat(real.equals(proxy))
.as("default equals() compares object identity; a proxy is never == the real instance")
.isFalse();
Set<ProxyPublisher> set = new HashSet<>();
set.add(real);
assertThat(set.contains(proxy))
.as("same underlying row, but the HashSet cannot tell -- this is the naive-equals() trap")
.isFalse();
em1.getTransaction().commit();
em1.close();
em2.getTransaction().commit();
em2.close();
}
}