Hibernate 8 + Jakarta Persistence 4: EntityAgent and stateless sessions demo
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b7jUQrypvpE1ix1k7V
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
package com.ankurm.agent;
|
||||
|
||||
import jakarta.persistence.EntityAgent;
|
||||
import org.hibernate.Hibernate;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Lazy associations are not loaded for you; fetch() loads them on request. */
|
||||
class Demo03Test {
|
||||
|
||||
@Test
|
||||
void lazyAssociationsNeedFetch() {
|
||||
try (Lab lab = new Lab(); Transcript t = new Transcript("03-lazy-associations-and-fetch")) {
|
||||
lab.seed();
|
||||
|
||||
lab.sf.runInTransaction(EntityAgent.class, a -> {
|
||||
Book b = a.get(Book.class, "978-1");
|
||||
boolean init = Hibernate.isInitialized(b.publisher);
|
||||
t.line("agent.get(Book): publisher initialized? %s", init);
|
||||
assertFalse(init);
|
||||
|
||||
Object viaGetter;
|
||||
try {
|
||||
viaGetter = b.publisher.getName();
|
||||
} catch (RuntimeException e) {
|
||||
viaGetter = e.getClass().getSimpleName();
|
||||
}
|
||||
t.line("book.publisher.getName() before fetch -> %s", viaGetter);
|
||||
|
||||
lab.resetSql();
|
||||
Publisher p = a.fetch(b.publisher);
|
||||
t.line("agent.fetch(book.publisher) -> getName() = %s", p.getName());
|
||||
t.line(" same object as book.publisher? %s, initialized now? %s",
|
||||
p == b.publisher, Hibernate.isInitialized(p));
|
||||
t.line(" reading the public field p.name instead -> %s", p.name);
|
||||
t.sql(" SQL", lab.sql());
|
||||
assertEquals("Manning", p.getName());
|
||||
assertEquals(1, lab.sql().size());
|
||||
});
|
||||
|
||||
lab.sf.runInTransaction(EntityAgent.class, a -> {
|
||||
Publisher p = a.get(Publisher.class, lab.sf.callInTransaction(em ->
|
||||
em.createQuery("select p.id from Publisher p", Long.class).getSingleResult()));
|
||||
boolean init = Hibernate.isInitialized(p.books);
|
||||
t.line("");
|
||||
t.line("agent.get(Publisher): books collection initialized? %s", init);
|
||||
assertFalse(init);
|
||||
|
||||
lab.resetSql();
|
||||
var books = a.fetch(p.books);
|
||||
t.line("agent.fetch(publisher.books) -> %d books", books.size());
|
||||
t.sql(" SQL", lab.sql());
|
||||
assertEquals(3, books.size());
|
||||
assertTrue(Hibernate.isInitialized(books));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user