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:
@@ -0,0 +1,181 @@
|
||||
package com.ankurm.hibernatedemo.association;
|
||||
|
||||
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 java.util.List;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.stat.Statistics;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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 ankurm.com post 4872, docs/12-association-mappings.md chapters "MultipleBagFetchException"
|
||||
* and "The cartesian-product trap".
|
||||
*/
|
||||
@SpringBootTest
|
||||
class BagFetchTest {
|
||||
|
||||
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
|
||||
|
||||
@Autowired
|
||||
private EntityManagerFactory emf;
|
||||
|
||||
@BeforeEach
|
||||
void cleanTables() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
em.createQuery("DELETE FROM BagBookL").executeUpdate();
|
||||
em.createQuery("DELETE FROM BagAwardL").executeUpdate();
|
||||
em.createQuery("DELETE FROM BagAuthorList").executeUpdate();
|
||||
em.createQuery("DELETE FROM BagBookS").executeUpdate();
|
||||
em.createQuery("DELETE FROM BagAwardS").executeUpdate();
|
||||
em.createQuery("DELETE FROM BagAuthorSet").executeUpdate();
|
||||
em.getTransaction().commit();
|
||||
em.close();
|
||||
}
|
||||
|
||||
private Statistics stats() {
|
||||
return emf.unwrap(SessionFactory.class).getStatistics();
|
||||
}
|
||||
|
||||
private Long seedListAuthor(int nBooks, int nAwards) {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
BagAuthorList author = new BagAuthorList("List Author");
|
||||
em.persist(author);
|
||||
for (int i = 0; i < nBooks; i++) {
|
||||
em.persist(new BagBookL("Book" + i, author));
|
||||
}
|
||||
for (int i = 0; i < nAwards; i++) {
|
||||
em.persist(new BagAwardL("Award" + i, author));
|
||||
}
|
||||
em.getTransaction().commit();
|
||||
Long id = author.getId();
|
||||
em.close();
|
||||
return id;
|
||||
}
|
||||
|
||||
private Long seedSetAuthor(int nBooks, int nAwards) {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
BagAuthorSet author = new BagAuthorSet("Set Author");
|
||||
em.persist(author);
|
||||
for (int i = 0; i < nBooks; i++) {
|
||||
em.persist(new BagBookS("Book" + i, author));
|
||||
}
|
||||
for (int i = 0; i < nAwards; i++) {
|
||||
em.persist(new BagAwardS("Award" + i, author));
|
||||
}
|
||||
em.getTransaction().commit();
|
||||
Long id = author.getId();
|
||||
em.close();
|
||||
return id;
|
||||
}
|
||||
|
||||
@Test
|
||||
void fetchJoiningTwoListsInOneQuery_throwsMultipleBagFetchException() {
|
||||
seedListAuthor(4, 3);
|
||||
EntityManager em = emf.createEntityManager();
|
||||
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () ->
|
||||
em.createQuery(
|
||||
"SELECT a FROM BagAuthorList a JOIN FETCH a.books JOIN FETCH a.awards",
|
||||
BagAuthorList.class).getResultList());
|
||||
|
||||
Throwable root = ex;
|
||||
while (root.getCause() != null && root.getCause() != root) {
|
||||
root = root.getCause();
|
||||
}
|
||||
DEMO.info("MultipleBagFetchException reproduction -- wrapper class: {}", ex.getClass().getName());
|
||||
DEMO.info("MultipleBagFetchException reproduction -- root cause class: {}", root.getClass().getName());
|
||||
DEMO.info("MultipleBagFetchException reproduction -- verbatim message: {}", root.getMessage());
|
||||
|
||||
assertThat(ex.getClass().getName()).as("EntityManager.createQuery(...).getResultList() wraps it as IllegalArgumentException, NOT PersistenceException")
|
||||
.isEqualTo("java.lang.IllegalArgumentException");
|
||||
assertThat(root.getClass().getName()).isEqualTo("org.hibernate.loader.MultipleBagFetchException");
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void fix1_useSetsInsteadOfLists_noExceptionOneQuery() {
|
||||
seedSetAuthor(4, 3);
|
||||
EntityManager em = emf.createEntityManager();
|
||||
stats().clear();
|
||||
|
||||
List<BagAuthorSet> authors = em.createQuery(
|
||||
"SELECT DISTINCT a FROM BagAuthorSet a JOIN FETCH a.books JOIN FETCH a.awards",
|
||||
BagAuthorSet.class)
|
||||
.getResultList();
|
||||
|
||||
long queries = stats().getPrepareStatementCount();
|
||||
DEMO.info("Fix #1 (Set instead of List): {} distinct authors returned, {} queries fired", authors.size(), queries);
|
||||
|
||||
assertThat(authors).hasSize(1);
|
||||
assertThat(authors.get(0).getBooks()).hasSize(4);
|
||||
assertThat(authors.get(0).getAwards()).hasSize(3);
|
||||
assertThat(queries).isEqualTo(1);
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void fix2_twoSeparateQueries_avoidsBagFetchExceptionEntirely() {
|
||||
Long id = seedListAuthor(4, 3);
|
||||
EntityManager em = emf.createEntityManager();
|
||||
stats().clear();
|
||||
|
||||
BagAuthorList author = em.createQuery(
|
||||
"SELECT a FROM BagAuthorList a JOIN FETCH a.books WHERE a.id = :id", BagAuthorList.class)
|
||||
.setParameter("id", id)
|
||||
.getSingleResult();
|
||||
// second, separate query for the other bag -- no exception because only one JOIN FETCH per query
|
||||
author = em.createQuery(
|
||||
"SELECT a FROM BagAuthorList a JOIN FETCH a.awards WHERE a.id = :id", BagAuthorList.class)
|
||||
.setParameter("id", id)
|
||||
.getSingleResult();
|
||||
|
||||
long queries = stats().getPrepareStatementCount();
|
||||
DEMO.info("Fix #2 (two queries): {} queries fired, books={}, awards={}",
|
||||
queries, author.getBooks().size(), author.getAwards().size());
|
||||
|
||||
assertThat(author.getBooks()).hasSize(4);
|
||||
assertThat(author.getAwards()).hasSize(3);
|
||||
assertThat(queries).as("one JOIN FETCH per query, run twice").isEqualTo(2);
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cartesianProduct_fetchJoiningTwoAllowedSetsExplodesRowCount() {
|
||||
seedSetAuthor(4, 3);
|
||||
EntityManager em = emf.createEntityManager();
|
||||
|
||||
// Raw SQL join without DISTINCT to see the true row count the database returns.
|
||||
Object rawCount = em.createNativeQuery(
|
||||
"SELECT COUNT(*) FROM bag_author_set a " +
|
||||
"JOIN bag_book_s b ON b.author_id = a.id " +
|
||||
"JOIN bag_award_s w ON w.author_id = a.id")
|
||||
.getSingleResult();
|
||||
long rawRowCount = ((Number) rawCount).longValue();
|
||||
|
||||
List<BagAuthorSet> entities = em.createQuery(
|
||||
"SELECT DISTINCT a FROM BagAuthorSet a JOIN FETCH a.books JOIN FETCH a.awards",
|
||||
BagAuthorSet.class)
|
||||
.getResultList();
|
||||
|
||||
DEMO.info("Cartesian product: 4 books x 3 awards for 1 author -> raw SQL join rows = {}, distinct entities returned = {}",
|
||||
rawRowCount, entities.size());
|
||||
|
||||
assertThat(rawRowCount).as("SQL returns one row per (book, award) pair: 4 x 3").isEqualTo(12);
|
||||
assertThat(entities).as("Hibernate's DISTINCT root-entity de-duplication collapses this back to 1 entity")
|
||||
.hasSize(1);
|
||||
assertThat(entities.get(0).getBooks()).hasSize(4);
|
||||
assertThat(entities.get(0).getAwards()).hasSize(3);
|
||||
em.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.ankurm.hibernatedemo.association;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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 ankurm.com post 4872, docs/12-association-mappings.md chapters "Cascade and orphanRemoval"
|
||||
* and "The owning side".
|
||||
*/
|
||||
@SpringBootTest
|
||||
class CascadeOrphanTest {
|
||||
|
||||
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
|
||||
|
||||
@Autowired
|
||||
private EntityManagerFactory emf;
|
||||
|
||||
@BeforeEach
|
||||
void cleanTables() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
em.createQuery("DELETE FROM CascadeBook").executeUpdate();
|
||||
em.createQuery("DELETE FROM CascadeAuthor").executeUpdate();
|
||||
em.createQuery("DELETE FROM NoOrphanBook").executeUpdate();
|
||||
em.createQuery("DELETE FROM NoOrphanAuthor").executeUpdate();
|
||||
em.getTransaction().commit();
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cascadeAllPlusOrphanRemoval_reassigningTheCollectionThrowsInsteadOfSilentlyDeleting() {
|
||||
// CORRECTION vs the common blog claim ("silently deletes what you did not expect"):
|
||||
// assigning a brand new List instance to a CascadeType.ALL + orphanRemoval=true
|
||||
// collection does NOT silently delete anything -- Hibernate detects the managed
|
||||
// collection was dereferenced and throws at flush/commit time instead.
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
CascadeAuthor author = new CascadeAuthor("Prolific Author");
|
||||
em.persist(author);
|
||||
em.persist(new CascadeBook("Book A", author));
|
||||
em.persist(new CascadeBook("Book B", author));
|
||||
em.getTransaction().commit();
|
||||
Long id = author.getId();
|
||||
em.close();
|
||||
|
||||
EntityManager em2 = emf.createEntityManager();
|
||||
em2.getTransaction().begin();
|
||||
CascadeAuthor managed = em2.find(CascadeAuthor.class, id);
|
||||
CascadeBook keep = managed.getBooks().get(0);
|
||||
managed.replaceBooksWithNewList(new ArrayList<>(List.of(keep))); // assigns a NEW ArrayList
|
||||
jakarta.persistence.RollbackException ex = org.junit.jupiter.api.Assertions.assertThrows(
|
||||
jakarta.persistence.RollbackException.class, () -> em2.getTransaction().commit());
|
||||
|
||||
Throwable root = ex.getCause();
|
||||
DEMO.info("cascade=ALL + orphanRemoval=true, reassigning the collection reference -- wrapper: {}", ex.getClass().getName());
|
||||
DEMO.info("cascade=ALL + orphanRemoval=true, reassigning the collection reference -- root cause: {}: {}",
|
||||
root.getClass().getName(), root.getMessage());
|
||||
em2.close();
|
||||
|
||||
assertThat(root.getClass().getName()).isEqualTo("org.hibernate.HibernateException");
|
||||
assertThat(root.getMessage()).contains("no longer referenced by the owning entity instance");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cascadeAllPlusOrphanRemoval_mutatingTheExistingCollectionDoesDeleteUnexpectedly() {
|
||||
// The scenario that DOES silently delete: mutating the SAME managed collection instance
|
||||
// (clear() then re-add the ones to keep) rather than reassigning a new List. This is
|
||||
// the realistic version of the "developer did not expect this" cascade trap.
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
CascadeAuthor author = new CascadeAuthor("Prolific Author 2");
|
||||
em.persist(author);
|
||||
em.persist(new CascadeBook("Book A", author));
|
||||
em.persist(new CascadeBook("Book B", author));
|
||||
em.persist(new CascadeBook("Book C", author));
|
||||
em.getTransaction().commit();
|
||||
Long id = author.getId();
|
||||
em.close();
|
||||
|
||||
EntityManager check1 = emf.createEntityManager();
|
||||
long before = ((Number) check1.createQuery("SELECT COUNT(b) FROM CascadeBook b WHERE b.author.id = :id")
|
||||
.setParameter("id", id).getSingleResult()).longValue();
|
||||
check1.close();
|
||||
assertThat(before).isEqualTo(3);
|
||||
|
||||
EntityManager em2 = emf.createEntityManager();
|
||||
em2.getTransaction().begin();
|
||||
CascadeAuthor managed = em2.find(CascadeAuthor.class, id);
|
||||
CascadeBook keep = managed.getBooks().stream().filter(b -> b.getTitle().equals("Book A")).findFirst().orElseThrow();
|
||||
// Mutate the EXISTING Hibernate-managed collection in place -- this is the pattern that
|
||||
// actually reaches production: "keep only Book A" implemented via removeIf.
|
||||
managed.getBooks().removeIf(b -> !b.getTitle().equals("Book A"));
|
||||
em2.getTransaction().commit();
|
||||
em2.close();
|
||||
|
||||
EntityManager check2 = emf.createEntityManager();
|
||||
long after = ((Number) check2.createQuery("SELECT COUNT(b) FROM CascadeBook b WHERE b.author.id = :id")
|
||||
.setParameter("id", id).getSingleResult()).longValue();
|
||||
DEMO.info("cascade=ALL + orphanRemoval=true, in-place removeIf(): books before={}, books after={}", before, after);
|
||||
check2.close();
|
||||
|
||||
assertThat(after)
|
||||
.as("orphanRemoval=true DELETEd Book B and Book C as soon as they left the managed collection")
|
||||
.isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noOrphanRemoval_removingFromCollectionAndFlushingDoesNothingToTheRow() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
NoOrphanAuthor author = new NoOrphanAuthor("Careful Author");
|
||||
em.persist(author);
|
||||
NoOrphanBook book1 = new NoOrphanBook("Keep Me", author);
|
||||
NoOrphanBook book2 = new NoOrphanBook("Remove Me From Collection", author);
|
||||
em.persist(book1);
|
||||
em.persist(book2);
|
||||
em.getTransaction().commit();
|
||||
Long authorId = author.getId();
|
||||
Long book2Id = book2.getId();
|
||||
em.close();
|
||||
|
||||
EntityManager em2 = emf.createEntityManager();
|
||||
em2.getTransaction().begin();
|
||||
NoOrphanAuthor managed = em2.find(NoOrphanAuthor.class, authorId);
|
||||
managed.getBooks().removeIf(b -> b.getId().equals(book2Id));
|
||||
em2.getTransaction().commit(); // no orphanRemoval, no cascade REMOVE -- nothing should happen to book2's row
|
||||
em2.close();
|
||||
|
||||
EntityManager check = emf.createEntityManager();
|
||||
NoOrphanBook stillThere = check.find(NoOrphanBook.class, book2Id);
|
||||
DEMO.info("orphanRemoval=false: after removing book2 from author.books and flushing, book2 row still exists = {}, author_id still = {}",
|
||||
stillThere != null, stillThere == null ? null : stillThere.getAuthor().getId());
|
||||
check.close();
|
||||
|
||||
assertThat(stillThere)
|
||||
.as("without orphanRemoval or cascade REMOVE, removing a child from the collection does not delete or unlink its row")
|
||||
.isNotNull();
|
||||
assertThat(stillThere.getAuthor().getId())
|
||||
.as("its FK is untouched -- still points at the same author")
|
||||
.isEqualTo(authorId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void owningSide_mutatingOnlyTheInverseCollectionNeverWritesTheForeignKey() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
NoOrphanAuthor author1 = new NoOrphanAuthor("Author One");
|
||||
NoOrphanAuthor author2 = new NoOrphanAuthor("Author Two");
|
||||
em.persist(author1);
|
||||
em.persist(author2);
|
||||
NoOrphanBook orphanBook = new NoOrphanBook("Unassigned Book", null);
|
||||
em.persist(orphanBook);
|
||||
em.getTransaction().commit();
|
||||
Long bookId = orphanBook.getId();
|
||||
Long author2Id = author2.getId();
|
||||
em.close();
|
||||
|
||||
// Mutate ONLY the inverse (mappedBy) side: add the book to author2's collection, but
|
||||
// never call book.setAuthor(author2) -- the collection is not the owning side.
|
||||
EntityManager em2 = emf.createEntityManager();
|
||||
em2.getTransaction().begin();
|
||||
NoOrphanAuthor managedAuthor2 = em2.find(NoOrphanAuthor.class, author2Id);
|
||||
NoOrphanBook managedBook = em2.find(NoOrphanBook.class, bookId);
|
||||
managedAuthor2.getBooks().add(managedBook); // inverse side only
|
||||
em2.getTransaction().commit();
|
||||
em2.close();
|
||||
|
||||
EntityManager check = emf.createEntityManager();
|
||||
NoOrphanBook reloaded = check.find(NoOrphanBook.class, bookId);
|
||||
DEMO.info("owning side test: mutated only author2.getBooks().add(book) (inverse side), book.author after flush = {}",
|
||||
reloaded.getAuthor() == null ? "null (FK not written)" : reloaded.getAuthor().getId());
|
||||
check.close();
|
||||
|
||||
assertThat(reloaded.getAuthor())
|
||||
.as("mutating only the inverse (mappedBy) collection never persists the association -- the owning side (Book.author) decides the FK")
|
||||
.isNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.ankurm.hibernatedemo.association;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import jakarta.persistence.EntityGraph;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import jakarta.persistence.TypedQuery;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.stat.Statistics;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* Backs ankurm.com post 4872, docs/12-association-mappings.md chapter "Counting the N+1".
|
||||
*
|
||||
* <p>Seeds 100 authors with 3 books each (301 rows total incl. authors) and counts real
|
||||
* {@code Statistics.getPrepareStatementCount()} for four strategies: naive lazy iteration,
|
||||
* JPQL fetch join, {@code @EntityGraph}, and {@code @BatchSize(10)}. Run with
|
||||
* {@code mvn -Dtest=NPlusOneTest test}.
|
||||
*/
|
||||
@SpringBootTest
|
||||
class NPlusOneTest {
|
||||
|
||||
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
|
||||
private static final int AUTHOR_COUNT = 100;
|
||||
private static final int BOOKS_PER_AUTHOR = 3;
|
||||
|
||||
@Autowired
|
||||
private EntityManagerFactory emf;
|
||||
|
||||
@BeforeEach
|
||||
void cleanTables() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
em.createQuery("DELETE FROM AssocBook").executeUpdate();
|
||||
em.createQuery("DELETE FROM AssocAuthor").executeUpdate();
|
||||
em.createQuery("DELETE FROM BatchBook").executeUpdate();
|
||||
em.createQuery("DELETE FROM BatchAuthor").executeUpdate();
|
||||
em.getTransaction().commit();
|
||||
em.close();
|
||||
}
|
||||
|
||||
private Statistics stats() {
|
||||
return emf.unwrap(SessionFactory.class).getStatistics();
|
||||
}
|
||||
|
||||
private void seedPlainAuthors() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
for (int a = 0; a < AUTHOR_COUNT; a++) {
|
||||
AssocAuthor author = new AssocAuthor("Author-" + a);
|
||||
em.persist(author);
|
||||
for (int b = 0; b < BOOKS_PER_AUTHOR; b++) {
|
||||
em.persist(new AssocBook("Book-" + a + "-" + b, author));
|
||||
}
|
||||
}
|
||||
em.getTransaction().commit();
|
||||
em.close();
|
||||
}
|
||||
|
||||
private void seedBatchAuthors() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
for (int a = 0; a < AUTHOR_COUNT; a++) {
|
||||
BatchAuthor author = new BatchAuthor("BatchAuthor-" + a);
|
||||
em.persist(author);
|
||||
for (int b = 0; b < BOOKS_PER_AUTHOR; b++) {
|
||||
em.persist(new BatchBook("BatchBook-" + a + "-" + b, author));
|
||||
}
|
||||
}
|
||||
em.getTransaction().commit();
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void naiveLazyIteration_firesOneQueryPerAuthor_theClassicNPlusOne() {
|
||||
seedPlainAuthors();
|
||||
EntityManager em = emf.createEntityManager();
|
||||
stats().clear();
|
||||
|
||||
List<AssocAuthor> authors = em.createQuery("SELECT a FROM AssocAuthor a", AssocAuthor.class).getResultList();
|
||||
long booksTouched = 0;
|
||||
for (AssocAuthor author : authors) {
|
||||
booksTouched += author.getBooks().size(); // triggers one SELECT per author
|
||||
}
|
||||
|
||||
long queries = stats().getPrepareStatementCount();
|
||||
DEMO.info("NAIVE lazy iteration: {} authors, {} queries (1 for authors + {} for their book collections), books touched = {}",
|
||||
authors.size(), queries, authors.size(), booksTouched);
|
||||
|
||||
assertThat(authors).hasSize(AUTHOR_COUNT);
|
||||
assertThat(queries)
|
||||
.as("1 query to load authors + 1 per author to lazily load its books == N+1")
|
||||
.isEqualTo(1 + AUTHOR_COUNT);
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jpqlFetchJoin_firesExactlyOneQuery() {
|
||||
seedPlainAuthors();
|
||||
EntityManager em = emf.createEntityManager();
|
||||
stats().clear();
|
||||
|
||||
List<AssocAuthor> authors = em.createQuery(
|
||||
"SELECT DISTINCT a FROM AssocAuthor a JOIN FETCH a.books", AssocAuthor.class)
|
||||
.getResultList();
|
||||
long booksTouched = 0;
|
||||
for (AssocAuthor author : authors) {
|
||||
booksTouched += author.getBooks().size(); // already initialised, no extra SELECT
|
||||
}
|
||||
|
||||
long queries = stats().getPrepareStatementCount();
|
||||
DEMO.info("JPQL JOIN FETCH: {} authors, {} queries, books touched = {}", authors.size(), queries, booksTouched);
|
||||
|
||||
assertThat(authors).hasSize(AUTHOR_COUNT);
|
||||
assertThat(queries).as("fetch join collapses N+1 into a single query").isEqualTo(1);
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void entityGraph_firesExactlyOneQuery() {
|
||||
seedPlainAuthors();
|
||||
EntityManager em = emf.createEntityManager();
|
||||
stats().clear();
|
||||
|
||||
EntityGraph<?> graph = em.getEntityGraph("AssocAuthor.books");
|
||||
TypedQuery<AssocAuthor> query = em.createQuery("SELECT a FROM AssocAuthor a", AssocAuthor.class);
|
||||
query.setHint("jakarta.persistence.fetchgraph", graph);
|
||||
List<AssocAuthor> authors = query.getResultList();
|
||||
long booksTouched = 0;
|
||||
for (AssocAuthor author : authors) {
|
||||
booksTouched += author.getBooks().size();
|
||||
}
|
||||
|
||||
long queries = stats().getPrepareStatementCount();
|
||||
DEMO.info("@EntityGraph (fetchgraph hint): {} authors, {} queries, books touched = {}", authors.size(), queries, booksTouched);
|
||||
|
||||
assertThat(authors).hasSize(AUTHOR_COUNT);
|
||||
assertThat(queries).as("entity graph fetch also collapses to a single query").isEqualTo(1);
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchSize10_collapsesNPlusOneIntoCeilNOverBatchSizePlusOne() {
|
||||
seedBatchAuthors();
|
||||
EntityManager em = emf.createEntityManager();
|
||||
stats().clear();
|
||||
|
||||
List<BatchAuthor> authors = em.createQuery("SELECT a FROM BatchAuthor a", BatchAuthor.class).getResultList();
|
||||
long booksTouched = 0;
|
||||
for (BatchAuthor author : authors) {
|
||||
booksTouched += author.getBooks().size(); // triggers 1 SELECT per 10 authors (batch fetch)
|
||||
}
|
||||
|
||||
long queries = stats().getPrepareStatementCount();
|
||||
// ceil(100 / 10) = 10 batch selects + 1 for the authors themselves = 11
|
||||
long expected = 1 + (long) Math.ceil(AUTHOR_COUNT / 10.0);
|
||||
DEMO.info("@BatchSize(10): {} authors, {} queries (expected {} = 1 + ceil({}/10)), books touched = {}",
|
||||
authors.size(), queries, expected, AUTHOR_COUNT, booksTouched);
|
||||
|
||||
assertThat(authors).hasSize(AUTHOR_COUNT);
|
||||
assertThat(queries).as("BatchSize(10) turns 101 queries into ceil(100/10)+1 = 11").isEqualTo(expected);
|
||||
em.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void printSideBySideComparisonTable() {
|
||||
// Re-derive each number in one place so the article table and the assertions above can
|
||||
// never silently drift apart.
|
||||
seedPlainAuthors();
|
||||
seedBatchAuthors();
|
||||
|
||||
EntityManager em = emf.createEntityManager();
|
||||
|
||||
stats().clear();
|
||||
List<AssocAuthor> naive = em.createQuery("SELECT a FROM AssocAuthor a", AssocAuthor.class).getResultList();
|
||||
naive.forEach(a -> a.getBooks().size());
|
||||
long naiveQ = stats().getPrepareStatementCount();
|
||||
|
||||
stats().clear();
|
||||
List<AssocAuthor> fetchJoin = em.createQuery(
|
||||
"SELECT DISTINCT a FROM AssocAuthor a JOIN FETCH a.books", AssocAuthor.class)
|
||||
.getResultList();
|
||||
fetchJoin.forEach(a -> a.getBooks().size());
|
||||
long fetchJoinQ = stats().getPrepareStatementCount();
|
||||
|
||||
stats().clear();
|
||||
EntityGraph<?> graph = em.getEntityGraph("AssocAuthor.books");
|
||||
TypedQuery<AssocAuthor> egQuery = em.createQuery("SELECT a FROM AssocAuthor a", AssocAuthor.class);
|
||||
egQuery.setHint("jakarta.persistence.fetchgraph", graph);
|
||||
List<AssocAuthor> eg = egQuery.getResultList();
|
||||
eg.forEach(a -> a.getBooks().size());
|
||||
long egQ = stats().getPrepareStatementCount();
|
||||
|
||||
stats().clear();
|
||||
List<BatchAuthor> batched = em.createQuery("SELECT a FROM BatchAuthor a", BatchAuthor.class).getResultList();
|
||||
batched.forEach(a -> a.getBooks().size());
|
||||
long batchQ = stats().getPrepareStatementCount();
|
||||
|
||||
DEMO.info("=== Side-by-side query counts for {} authors x {} books each ===", AUTHOR_COUNT, BOOKS_PER_AUTHOR);
|
||||
DEMO.info("naive lazy iteration : {} queries", naiveQ);
|
||||
DEMO.info("JPQL JOIN FETCH : {} queries", fetchJoinQ);
|
||||
DEMO.info("@EntityGraph : {} queries", egQ);
|
||||
DEMO.info("@BatchSize(10) : {} queries", batchQ);
|
||||
|
||||
assertThat(Map.of("naive", naiveQ, "fetchJoin", fetchJoinQ, "entityGraph", egQ, "batch10", batchQ))
|
||||
.isEqualTo(Map.of("naive", 101L, "fetchJoin", 1L, "entityGraph", 1L, "batch10", 11L));
|
||||
em.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.ankurm.hibernatedemo.association;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.stat.Statistics;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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 ankurm.com post 4872, docs/12-association-mappings.md chapter "The @OneToOne lazy trap".
|
||||
*
|
||||
* <p>{@link LazyUser#getProfile()} is the non-owning ("mappedBy") side of an optional
|
||||
* {@code @OneToOne}, declared {@code FetchType.LAZY}. Without bytecode enhancement, Hibernate
|
||||
* cannot build a lazy proxy for it (it has no FK column to defer against), so it fires an
|
||||
* eager extra SELECT regardless of the annotation. {@link MiUser}/{@link MiProfile} show the
|
||||
* {@code @MapsId} fix: don't map the inverse side at all, look the child up on demand by the
|
||||
* shared primary key.
|
||||
*/
|
||||
@SpringBootTest
|
||||
class OneToOneLazyTest {
|
||||
|
||||
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
|
||||
|
||||
@Autowired
|
||||
private EntityManagerFactory emf;
|
||||
|
||||
@BeforeEach
|
||||
void cleanTables() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
em.createQuery("DELETE FROM LazyProfile").executeUpdate();
|
||||
em.createQuery("DELETE FROM LazyUser").executeUpdate();
|
||||
em.createQuery("DELETE FROM MiProfile").executeUpdate();
|
||||
em.createQuery("DELETE FROM MiUser").executeUpdate();
|
||||
em.getTransaction().commit();
|
||||
em.close();
|
||||
}
|
||||
|
||||
private Statistics stats() {
|
||||
return emf.unwrap(SessionFactory.class).getStatistics();
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappedBySideOneToOne_firesExtraSelectEvenThoughItIsDeclaredLazy() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
LazyUser user = new LazyUser("alice");
|
||||
em.persist(user);
|
||||
LazyProfile profile = new LazyProfile("bio text", user);
|
||||
user.setProfile(profile);
|
||||
em.persist(profile);
|
||||
em.getTransaction().commit();
|
||||
Long id = user.getId();
|
||||
em.close();
|
||||
|
||||
EntityManager em2 = emf.createEntityManager();
|
||||
stats().clear();
|
||||
LazyUser loaded = em2.find(LazyUser.class, id);
|
||||
long queriesAfterFind = stats().getPrepareStatementCount();
|
||||
DEMO.info("LazyUser.find(): {} queries fired BEFORE touching getProfile() at all (expected 2: user + eager profile join/select)", queriesAfterFind);
|
||||
|
||||
// Note: the extra SELECT for profile already happened during find(), not here.
|
||||
String bio = loaded.getProfile() == null ? null : "loaded";
|
||||
long queriesAfterAccess = stats().getPrepareStatementCount();
|
||||
DEMO.info("after touching getProfile(): {} queries total (profile={})", queriesAfterAccess, bio);
|
||||
|
||||
assertThat(queriesAfterFind)
|
||||
.as("mappedBy @OneToOne(LAZY) still fires the profile SELECT immediately during find(), not on first access")
|
||||
.isEqualTo(2);
|
||||
assertThat(queriesAfterAccess).as("no further query needed -- it already ran eagerly").isEqualTo(2);
|
||||
em2.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapsIdFix_loadingUserAloneFiresOnlyOneQuery_profileFetchedOnDemand() {
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
MiUser user = new MiUser("bob");
|
||||
em.persist(user);
|
||||
em.flush(); // need the generated id before building the shared-PK child
|
||||
MiProfile profile = new MiProfile("bob's bio", user);
|
||||
em.persist(profile);
|
||||
em.getTransaction().commit();
|
||||
Long id = user.getId();
|
||||
em.close();
|
||||
|
||||
EntityManager em2 = emf.createEntityManager();
|
||||
stats().clear();
|
||||
MiUser loaded = em2.find(MiUser.class, id);
|
||||
long queriesForUserOnly = stats().getPrepareStatementCount();
|
||||
DEMO.info("MiUser.find() (no mappedBy field at all): {} query", queriesForUserOnly);
|
||||
|
||||
// Fetch profile ONLY when actually needed, using the shared PK -- no proxy required.
|
||||
MiProfile profileOnDemand = em2.find(MiProfile.class, id);
|
||||
long queriesAfterExplicitProfileFetch = stats().getPrepareStatementCount();
|
||||
DEMO.info("explicit MiProfile.find() by shared PK when actually needed: {} total queries", queriesAfterExplicitProfileFetch);
|
||||
|
||||
assertThat(loaded).isNotNull();
|
||||
assertThat(queriesForUserOnly)
|
||||
.as("with @MapsId and no inverse mappedBy field, loading the user alone costs exactly 1 query")
|
||||
.isEqualTo(1);
|
||||
assertThat(profileOnDemand.getId()).isEqualTo(id);
|
||||
assertThat(queriesAfterExplicitProfileFetch)
|
||||
.as("fetching the profile only happens when the code actually asks for it")
|
||||
.isEqualTo(2);
|
||||
em2.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user