Add one-to-many module: @OneToMany in Hibernate 7.4.16.Final (unidirectional join table vs @JoinColumn vs mappedBy, Set vs List removal cost, sync helper, fetch defaults, N+1, MultipleBagFetchException fixes, id-hashCode trap)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4H5ph3J7k2MJnRuVH
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
bdae169002
commit
eab5461d86
@@ -0,0 +1,171 @@
|
||||
package com.ankurm.onetomany;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistry;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.resource.jdbc.spi.StatementInspector;
|
||||
|
||||
/** Plain Hibernate bootstrap on an in-memory H2 (no Spring, no persistence.xml) plus helpers that record the SQL Hibernate sends. */
|
||||
final class Db implements AutoCloseable {
|
||||
|
||||
/** Every SQL string Hibernate prepares, in order (raw JDBC issued by the tests is not recorded). */
|
||||
private static final List<String> LOG = new ArrayList<>();
|
||||
|
||||
public static class Recorder implements StatementInspector {
|
||||
@Override
|
||||
public String inspect(String sql) {
|
||||
synchronized (LOG) {
|
||||
LOG.add(sql.replaceAll("\\s+", " ").trim());
|
||||
}
|
||||
return sql;
|
||||
}
|
||||
}
|
||||
|
||||
private final SessionFactory sf;
|
||||
|
||||
private Db(SessionFactory sf) {
|
||||
this.sf = sf;
|
||||
}
|
||||
|
||||
static Db open(Class<?>... entities) {
|
||||
return open(Map.of(), entities);
|
||||
}
|
||||
|
||||
static Db open(Map<String, String> extra, Class<?>... entities) {
|
||||
StandardServiceRegistryBuilder b = new StandardServiceRegistryBuilder()
|
||||
.applySetting("hibernate.connection.url", "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1")
|
||||
.applySetting("hibernate.connection.username", "sa")
|
||||
.applySetting("hibernate.hbm2ddl.auto", "create-drop")
|
||||
.applySetting("hibernate.generate_statistics", "true")
|
||||
.applySetting("hibernate.session_factory.statement_inspector", Recorder.class.getName());
|
||||
extra.forEach(b::applySetting);
|
||||
StandardServiceRegistry registry = b.build();
|
||||
MetadataSources sources = new MetadataSources(registry);
|
||||
for (Class<?> e : entities) {
|
||||
sources.addAnnotatedClass(e);
|
||||
}
|
||||
return new Db(sources.buildMetadata().buildSessionFactory());
|
||||
}
|
||||
|
||||
SessionFactory sf() {
|
||||
return sf;
|
||||
}
|
||||
|
||||
/** Runs {@code work} in its own session and transaction. */
|
||||
<T> T tx(Function<Session, T> work) {
|
||||
try (Session s = sf.openSession()) {
|
||||
var t = s.beginTransaction();
|
||||
try {
|
||||
T r = work.apply(s);
|
||||
t.commit();
|
||||
return r;
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
if (t.isActive()) {
|
||||
t.rollback();
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void txv(Consumer<Session> work) {
|
||||
tx(s -> {
|
||||
work.accept(s);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Runs the action and returns the SQL Hibernate prepared while it ran. */
|
||||
static List<String> sql(Runnable action) {
|
||||
synchronized (LOG) {
|
||||
LOG.clear();
|
||||
}
|
||||
action.run();
|
||||
synchronized (LOG) {
|
||||
return new ArrayList<>(LOG);
|
||||
}
|
||||
}
|
||||
|
||||
/** Raw JDBC query, each row rendered as {@code a | b | c}. */
|
||||
List<String> rows(String sql) {
|
||||
return tx(s -> s.doReturningWork(cn -> {
|
||||
List<String> out = new ArrayList<>();
|
||||
try (var st = cn.createStatement(); ResultSet rs = st.executeQuery(sql)) {
|
||||
ResultSetMetaData md = rs.getMetaData();
|
||||
while (rs.next()) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for (int i = 1; i <= md.getColumnCount(); i++) {
|
||||
if (i > 1) {
|
||||
b.append(" | ");
|
||||
}
|
||||
b.append(rs.getObject(i));
|
||||
}
|
||||
out.add(b.toString());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}));
|
||||
}
|
||||
|
||||
/** Raw JDBC statement (DDL or DML), invisible to the SQL recorder. */
|
||||
void exec(String sql) {
|
||||
txv(s -> s.doWork(cn -> {
|
||||
try (var st = cn.createStatement()) {
|
||||
st.execute(sql);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
long count(String table) {
|
||||
return Long.parseLong(rows("select count(*) from " + table).get(0));
|
||||
}
|
||||
|
||||
/** The foreign keys of one table with their ON DELETE rule, straight from H2's information schema. */
|
||||
List<String> foreignKeys(String table) {
|
||||
return rows("select tc.constraint_name, rc.delete_rule from information_schema.table_constraints tc "
|
||||
+ "join information_schema.referential_constraints rc on rc.constraint_name = tc.constraint_name "
|
||||
+ "and rc.constraint_schema = tc.constraint_schema "
|
||||
+ "where tc.table_name = '" + table.toUpperCase() + "' and tc.constraint_type = 'FOREIGN KEY' order by 1");
|
||||
}
|
||||
|
||||
static Throwable root(Throwable t) {
|
||||
while (t.getCause() != null && t.getCause() != t) {
|
||||
t = t.getCause();
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Exception chain on one line, class names only, so transcripts stay stable. */
|
||||
static String chain(Throwable t) {
|
||||
StringBuilder sb = new StringBuilder(t.getClass().getName());
|
||||
Throwable c = t.getCause();
|
||||
while (c != null && c != t) {
|
||||
sb.append(" <- ").append(c.getClass().getName());
|
||||
t = c;
|
||||
c = c.getCause();
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
static String firstLine(Throwable t) {
|
||||
return String.valueOf(t.getMessage()).lines().findFirst().orElse("");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (sf.isOpen()) {
|
||||
sf.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.ankurm.onetomany;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.onetomany.Variants.*;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Same job (one parent, two children) mapped four ways: what tables exist and what SQL the insert sends. */
|
||||
class T01_ShapesTest {
|
||||
|
||||
private static String sqlOf(List<String> sql) {
|
||||
return String.join("\n", sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fourShapes() {
|
||||
Transcript t = new Transcript("01-shapes", "One parent, two children, four mappings: tables and insert SQL");
|
||||
|
||||
t.heading("A. Unidirectional, plain @OneToMany (no mappedBy, no @JoinColumn)");
|
||||
try (Db db = Db.open(JtListParent.class, JtChild.class)) {
|
||||
t.line("tables: " + db.rows("select table_name from information_schema.tables where table_schema = 'PUBLIC' order by 1"));
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
JtListParent p = new JtListParent();
|
||||
p.children.add(new JtChild("a"));
|
||||
p.children.add(new JtChild("b"));
|
||||
s.persist(p);
|
||||
}));
|
||||
t.step("persist(parent with 2 children); commit", sql);
|
||||
assertThat(sql).hasSize(5); // 1 parent + 2 children + 2 join rows
|
||||
assertThat(sqlOf(sql)).contains("JtListParent_JtChild");
|
||||
}
|
||||
|
||||
t.heading("B. Unidirectional with @JoinColumn(name = \"parent_id\")");
|
||||
try (Db db = Db.open(JcListParent.class, JcChild.class)) {
|
||||
t.line("tables: " + db.rows("select table_name from information_schema.tables where table_schema = 'PUBLIC' order by 1"));
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
JcListParent p = new JcListParent();
|
||||
p.children.add(new JcChild("a"));
|
||||
p.children.add(new JcChild("b"));
|
||||
s.persist(p);
|
||||
}));
|
||||
t.step("persist(parent with 2 children); commit", sql);
|
||||
assertThat(sql).hasSize(5); // 1 parent + 2 children + 2 updates of parent_id
|
||||
assertThat(sqlOf(sql)).contains("update JcChild set parent_id");
|
||||
}
|
||||
|
||||
t.heading("C. Bidirectional, mappedBy, child owns the foreign key");
|
||||
try (Db db = Db.open(Department.class, Employee.class)) {
|
||||
t.line("tables: " + db.rows("select table_name from information_schema.tables where table_schema = 'PUBLIC' order by 1"));
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
Department d = new Department("AI Research");
|
||||
d.addEmployee(new Employee("Ankur"));
|
||||
d.addEmployee(new Employee("Asha"));
|
||||
s.persist(d);
|
||||
}));
|
||||
t.step("persist(department with 2 employees); commit", sql);
|
||||
assertThat(sql).hasSize(3);
|
||||
assertThat(sqlOf(sql)).doesNotContain("update");
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.ankurm.onetomany;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.onetomany.Variants.*;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Remove one child from a collection of 5, then from a collection of 50: how many statements, per mapping. */
|
||||
class T02_BagVsSetTest {
|
||||
|
||||
private static final int[] SIZES = { 5, 50 };
|
||||
|
||||
@Test
|
||||
void removeOneChild() {
|
||||
Transcript t = new Transcript("02-bag-vs-set", "Removing ONE child: statements sent, per mapping");
|
||||
t.line("Each row: mapping | children before | statements on remove(one) + flush() | of which DELETE | of which INSERT | of which UPDATE");
|
||||
|
||||
for (int n : SIZES) {
|
||||
t.heading(n + " children");
|
||||
|
||||
// Unidirectional join table, List (bag)
|
||||
try (Db db = Db.open(JtListParent.class, JtChild.class)) {
|
||||
Long id = db.tx(s -> {
|
||||
JtListParent p = new JtListParent();
|
||||
for (int i = 0; i < n; i++) {
|
||||
p.children.add(new JtChild("c" + i));
|
||||
}
|
||||
s.persist(p);
|
||||
return p.id;
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
s.find(JtListParent.class, id).children.remove(0);
|
||||
s.flush();
|
||||
}));
|
||||
row(t, "join table, List (bag)", n, sql);
|
||||
assertThat(count(sql, "insert")).isEqualTo(n - 1); // every surviving child's join row is re-inserted
|
||||
if (n == 5) {
|
||||
t.step("join table, List, n=5", sql);
|
||||
}
|
||||
assertThat(count(sql, "delete")).isEqualTo(2); // join rows for the parent, then the orphan child
|
||||
}
|
||||
|
||||
// Unidirectional join table, Set
|
||||
try (Db db = Db.open(JtSetParent.class, JtChild.class)) {
|
||||
Long id = db.tx(s -> {
|
||||
JtSetParent p = new JtSetParent();
|
||||
for (int i = 0; i < n; i++) {
|
||||
p.children.add(new JtChild("c" + i));
|
||||
}
|
||||
s.persist(p);
|
||||
return p.id;
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
JtSetParent p = s.find(JtSetParent.class, id);
|
||||
p.children.remove(p.children.iterator().next());
|
||||
s.flush();
|
||||
}));
|
||||
row(t, "join table, Set", n, sql);
|
||||
if (n == 5) {
|
||||
t.step("join table, Set, n=5", sql);
|
||||
}
|
||||
assertThat(count(sql, "insert")).isZero();
|
||||
}
|
||||
|
||||
// Unidirectional @JoinColumn, List
|
||||
try (Db db = Db.open(JcListParent.class, JcChild.class)) {
|
||||
Long id = db.tx(s -> {
|
||||
JcListParent p = new JcListParent();
|
||||
for (int i = 0; i < n; i++) {
|
||||
p.children.add(new JcChild("c" + i));
|
||||
}
|
||||
s.persist(p);
|
||||
return p.id;
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
s.find(JcListParent.class, id).children.remove(0);
|
||||
s.flush();
|
||||
}));
|
||||
row(t, "@JoinColumn, List (bag)", n, sql);
|
||||
if (n == 5) {
|
||||
t.step("@JoinColumn, List, n=5", sql);
|
||||
}
|
||||
}
|
||||
|
||||
// @JoinColumn + @OrderColumn
|
||||
try (Db db = Db.open(OcParent.class, OcChild.class)) {
|
||||
Long id = db.tx(s -> {
|
||||
OcParent p = new OcParent();
|
||||
for (int i = 0; i < n; i++) {
|
||||
p.children.add(new OcChild("c" + i));
|
||||
}
|
||||
s.persist(p);
|
||||
return p.id;
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
s.find(OcParent.class, id).children.remove(0); // first element: worst case for positions
|
||||
s.flush();
|
||||
}));
|
||||
row(t, "@JoinColumn + @OrderColumn, remove FIRST", n, sql);
|
||||
assertThat(count(sql, "update")).isEqualTo(2 * n - 1); // n nulled out, then n-1 re-numbered
|
||||
if (n == 5) {
|
||||
t.step("@OrderColumn, remove first, n=5", sql);
|
||||
}
|
||||
}
|
||||
|
||||
// bidirectional List
|
||||
try (Db db = Db.open(BiListDept.class, BiListEmp.class)) {
|
||||
Long id = db.tx(s -> {
|
||||
BiListDept p = new BiListDept();
|
||||
for (int i = 0; i < n; i++) {
|
||||
p.add(new BiListEmp("c" + i));
|
||||
}
|
||||
s.persist(p);
|
||||
return p.id;
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
s.find(BiListDept.class, id).employees.remove(0);
|
||||
s.flush();
|
||||
}));
|
||||
row(t, "bidirectional mappedBy, List (bag)", n, sql);
|
||||
if (n == 5) {
|
||||
t.step("bidirectional, List, n=5", sql);
|
||||
}
|
||||
assertThat(count(sql, "delete")).isEqualTo(1);
|
||||
assertThat(count(sql, "insert")).isZero();
|
||||
}
|
||||
|
||||
// bidirectional Set
|
||||
try (Db db = Db.open(Department.class, Employee.class)) {
|
||||
Long id = db.tx(s -> {
|
||||
Department p = new Department("d");
|
||||
for (int i = 0; i < n; i++) {
|
||||
p.addEmployee(new Employee("c" + i));
|
||||
}
|
||||
s.persist(p);
|
||||
return p.getId();
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
Department d = s.find(Department.class, id);
|
||||
d.removeEmployee(d.getEmployees().iterator().next());
|
||||
s.flush();
|
||||
}));
|
||||
row(t, "bidirectional mappedBy, Set", n, sql);
|
||||
if (n == 5) {
|
||||
t.step("bidirectional, Set, n=5", sql);
|
||||
}
|
||||
assertThat(count(sql, "delete")).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
|
||||
static long count(List<String> sql, String verb) {
|
||||
return sql.stream().filter(s -> s.toLowerCase().startsWith(verb)).count();
|
||||
}
|
||||
|
||||
private static void row(Transcript t, String mapping, int n, List<String> sql) {
|
||||
// statements = everything Hibernate prepared, including the SELECTs that loaded the collection
|
||||
long writes = count(sql, "delete") + count(sql, "insert") + count(sql, "update");
|
||||
t.line(String.format("%-40s | %3d | writes=%3d | delete=%d insert=%d update=%d", mapping, n, writes,
|
||||
count(sql, "delete"), count(sql, "insert"), count(sql, "update")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ankurm.onetomany;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.onetomany.Variants.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Bidirectional: what the database holds when only ONE side is updated. */
|
||||
class T03_SyncHelperTest {
|
||||
|
||||
@Test
|
||||
void withAndWithoutTheHelper() {
|
||||
Transcript t = new Transcript("03-sync-helper", "Bidirectional sync: parent side only vs helper method");
|
||||
|
||||
try (Db db = Db.open(BiListDept.class, BiListEmp.class)) {
|
||||
Long[] ids = new Long[2];
|
||||
db.txv(s -> {
|
||||
BiListDept d = new BiListDept();
|
||||
BiListEmp e = new BiListEmp("no-helper");
|
||||
d.employees.add(e); // parent side only; e.department stays null
|
||||
s.persist(d);
|
||||
ids[0] = e.id;
|
||||
t.line("in memory, before flush: e.department == " + e.department);
|
||||
assertThat(e.department).isNull();
|
||||
});
|
||||
t.line("database after commit: employee " + ids[0] + " has dept_id = "
|
||||
+ db.rows("select dept_id from BiListEmp where id = " + ids[0]).get(0));
|
||||
assertThat(db.rows("select dept_id from BiListEmp where id = " + ids[0]).get(0)).isEqualTo("null");
|
||||
|
||||
db.txv(s -> {
|
||||
BiListDept d = new BiListDept();
|
||||
BiListEmp e = new BiListEmp("with-helper");
|
||||
d.add(e); // both sides
|
||||
s.persist(d);
|
||||
ids[1] = e.id;
|
||||
});
|
||||
t.line("database after commit: employee " + ids[1] + " (via helper) has dept_id = "
|
||||
+ db.rows("select dept_id from BiListEmp where id = " + ids[1]).get(0));
|
||||
assertThat(db.rows("select dept_id from BiListEmp where id = " + ids[1]).get(0)).isNotEqualTo("null");
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.ankurm.onetomany;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.onetomany.Variants.*;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The fetch defaults, then N+1 and its two fixes, with statement counts. */
|
||||
class T04_FetchTest {
|
||||
|
||||
@Test
|
||||
void defaults() {
|
||||
Transcript t = new Transcript("04-fetch-defaults", "JPA fetch defaults: @OneToMany is LAZY, @ManyToOne is EAGER");
|
||||
try (Db db = Db.open(EagerDepartment.class, EagerEmployee.class)) {
|
||||
Long empId = db.tx(s -> {
|
||||
EagerDepartment d = new EagerDepartment("AI");
|
||||
EagerEmployee a = new EagerEmployee("a", d);
|
||||
EagerEmployee b = new EagerEmployee("b", d);
|
||||
d.getEmployees().add(a);
|
||||
d.getEmployees().add(b);
|
||||
s.persist(d);
|
||||
return a.getId();
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> s.find(EagerEmployee.class, empId)));
|
||||
t.step("find(EagerEmployee) with @ManyToOne at its default", sql);
|
||||
assertThat(sql).hasSize(1);
|
||||
assertThat(sql.get(0)).contains("join EagerDepartment");
|
||||
assertThat(sql.get(0)).doesNotContain("EagerEmployee e1_0 join EagerEmployee");
|
||||
|
||||
Long deptId = db.tx(s -> s.createQuery("select d.id from EagerDepartment d", Long.class).getSingleResult());
|
||||
sql = Db.sql(() -> db.txv(s -> s.find(EagerDepartment.class, deptId)));
|
||||
t.step("find(EagerDepartment): the @OneToMany collection is not loaded", sql);
|
||||
assertThat(sql).hasSize(1);
|
||||
assertThat(sql.get(0)).doesNotContain("EagerEmployee");
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nPlusOne() {
|
||||
Transcript t = new Transcript("05-n-plus-one", "N+1 and its fixes: statements sent for 5 departments with 3 employees each");
|
||||
try (Db db = Db.open(Department.class, Employee.class)) {
|
||||
db.txv(s -> {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
Department d = new Department("d" + i);
|
||||
for (int j = 0; j < 3; j++) {
|
||||
d.addEmployee(new Employee("e" + i + j));
|
||||
}
|
||||
s.persist(d);
|
||||
}
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
for (Department d : s.createQuery("select d from Department d", Department.class).getResultList()) {
|
||||
d.getEmployees().size();
|
||||
}
|
||||
}));
|
||||
t.step("naive: query departments, then touch each employees collection", sql);
|
||||
assertThat(sql).hasSize(6);
|
||||
|
||||
sql = Db.sql(() -> db.txv(s -> {
|
||||
List<Department> ds = s.createQuery("select d from Department d left join fetch d.employees", Department.class).getResultList();
|
||||
ds.forEach(d -> d.getEmployees().size());
|
||||
t.line(" departments returned: " + ds.size() + " (no DISTINCT needed in Hibernate 7)");
|
||||
assertThat(ds).hasSize(5);
|
||||
}));
|
||||
t.step("fix 1: left join fetch d.employees", sql);
|
||||
assertThat(sql).hasSize(1);
|
||||
}
|
||||
|
||||
try (Db db = Db.open(BatchDept.class, BatchEmp.class, BatchProject.class)) {
|
||||
db.txv(s -> {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
BatchDept d = new BatchDept();
|
||||
for (int j = 0; j < 3; j++) {
|
||||
BatchEmp e = new BatchEmp("e" + i + j);
|
||||
e.department = d;
|
||||
d.employees.add(e);
|
||||
}
|
||||
s.persist(d);
|
||||
}
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
for (BatchDept d : s.createQuery("select d from BatchDept d", BatchDept.class).getResultList()) {
|
||||
d.employees.size();
|
||||
}
|
||||
}));
|
||||
t.step("fix 2: @BatchSize(size = 20) on the collection, same loop as the naive one", sql);
|
||||
assertThat(sql).hasSize(2);
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.ankurm.onetomany;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.ankurm.onetomany.Variants.*;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Two List collections, one JOIN FETCH each: the exception and the three fixes. */
|
||||
class T05_MultipleBagTest {
|
||||
|
||||
@Test
|
||||
void exceptionAndFixes() {
|
||||
Transcript t = new Transcript("06-multiple-bag", "MultipleBagFetchException and three fixes (3 employees, 4 projects per department)");
|
||||
|
||||
t.heading("The failure: two Lists, two join fetches");
|
||||
try (Db db = Db.open(BagDept.class, BagEmp.class, BagProject.class)) {
|
||||
db.txv(s -> {
|
||||
BagDept d = new BagDept();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
BagEmp e = new BagEmp("e" + i);
|
||||
e.department = d;
|
||||
d.employees.add(e);
|
||||
}
|
||||
for (int i = 0; i < 4; i++) {
|
||||
BagProject p = new BagProject("p" + i);
|
||||
p.department = d;
|
||||
d.projects.add(p);
|
||||
}
|
||||
s.persist(d);
|
||||
});
|
||||
Throwable[] caught = new Throwable[1];
|
||||
List<String> sql = Db.sql(() -> {
|
||||
try {
|
||||
db.txv(s -> s.createQuery("select d from BagDept d left join fetch d.employees left join fetch d.projects", BagDept.class).getResultList());
|
||||
}
|
||||
catch (RuntimeException ex) {
|
||||
caught[0] = ex;
|
||||
}
|
||||
});
|
||||
assertThat(caught[0]).isNotNull();
|
||||
t.line("exception: " + Db.chain(caught[0]));
|
||||
t.line("message: " + Db.firstLine(caught[0]));
|
||||
t.step("SQL sent before the exception", sql);
|
||||
assertThat(Db.chain(caught[0])).contains("MultipleBagFetchException");
|
||||
|
||||
t.heading("Fix 2: split into two queries (same Lists)");
|
||||
sql = Db.sql(() -> db.txv(s -> {
|
||||
List<BagDept> ds = s.createQuery("select d from BagDept d left join fetch d.employees", BagDept.class).getResultList();
|
||||
ds = s.createQuery("select d from BagDept d left join fetch d.projects where d in :ds", BagDept.class).setParameter("ds", ds).getResultList();
|
||||
t.line(" employees=" + ds.get(0).employees.size() + " projects=" + ds.get(0).projects.size());
|
||||
assertThat(ds.get(0).employees).hasSize(3);
|
||||
assertThat(ds.get(0).projects).hasSize(4);
|
||||
}));
|
||||
t.step("two queries, one collection each", sql);
|
||||
assertThat(sql).hasSize(2);
|
||||
}
|
||||
|
||||
t.heading("Fix 1: Set instead of List");
|
||||
try (Db db = Db.open(SetDept.class, SetEmp.class, SetProject.class)) {
|
||||
db.txv(s -> {
|
||||
SetDept d = new SetDept();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
SetEmp e = new SetEmp("e" + i);
|
||||
e.department = d;
|
||||
d.employees.add(e);
|
||||
}
|
||||
for (int i = 0; i < 4; i++) {
|
||||
SetProject p = new SetProject("p" + i);
|
||||
p.department = d;
|
||||
d.projects.add(p);
|
||||
}
|
||||
s.persist(d);
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
SetDept d = s.createQuery("select d from SetDept d left join fetch d.employees left join fetch d.projects", SetDept.class).getSingleResult();
|
||||
t.line(" employees=" + d.employees.size() + " projects=" + d.projects.size());
|
||||
assertThat(d.employees).hasSize(3);
|
||||
assertThat(d.projects).hasSize(4);
|
||||
}));
|
||||
t.step("one query, two join fetches", sql);
|
||||
assertThat(sql).hasSize(1);
|
||||
t.line("rows the database returned for that one query: "
|
||||
+ db.rows("select count(*) from SetDept d left join SetEmp e on e.dept_id = d.id left join SetProject p on p.dept_id = d.id").get(0)
|
||||
+ " (3 x 4: the Cartesian product Hibernate then folds back into 3 + 4 objects)");
|
||||
}
|
||||
|
||||
t.heading("Fix 3: keep Lists, drop the join fetch, add @BatchSize");
|
||||
try (Db db = Db.open(BatchDept.class, BatchEmp.class, BatchProject.class)) {
|
||||
db.txv(s -> {
|
||||
BatchDept d = new BatchDept();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
BatchEmp e = new BatchEmp("e" + i);
|
||||
e.department = d;
|
||||
d.employees.add(e);
|
||||
}
|
||||
for (int i = 0; i < 4; i++) {
|
||||
BatchProject p = new BatchProject("p" + i);
|
||||
p.department = d;
|
||||
d.projects.add(p);
|
||||
}
|
||||
s.persist(d);
|
||||
});
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
BatchDept d = s.createQuery("select d from BatchDept d", BatchDept.class).getSingleResult();
|
||||
t.line(" employees=" + d.employees.size() + " projects=" + d.projects.size());
|
||||
}));
|
||||
t.step("query the parents, touch both collections", sql);
|
||||
assertThat(sql).hasSize(3);
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.ankurm.onetomany;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ankurm.onetomany.Variants.*;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** A Set is only as good as its children's hashCode. An id-based hashCode changes when persist() assigns the id. */
|
||||
class T06_IdHashCodeTest {
|
||||
|
||||
@Test
|
||||
void idBasedHashCode() {
|
||||
Transcript t = new Transcript("07-id-hashcode", "Set + id-based hashCode vs UUID-based hashCode: remove() after persist");
|
||||
|
||||
try (Db db = Db.open(IdHashOwner.class, IdHashChild.class)) {
|
||||
IdHashOwner[] holder = new IdHashOwner[1];
|
||||
boolean[] removed = new boolean[1];
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
IdHashOwner o = new IdHashOwner();
|
||||
IdHashChild c = new IdHashChild("c");
|
||||
o.add(c); // hashCode computed here: id is null
|
||||
s.persist(o); // IDENTITY insert assigns the id: hashCode changes
|
||||
removed[0] = o.children.remove(c);
|
||||
s.flush();
|
||||
holder[0] = o;
|
||||
}));
|
||||
t.line("id-based hashCode: Set.remove(child) returned " + removed[0]);
|
||||
t.step("commit", sql);
|
||||
t.line("rows left in IdHashChild: " + db.count("IdHashChild") + " (the child was NOT removed, so orphanRemoval never saw it)");
|
||||
assertThat(removed[0]).isFalse();
|
||||
assertThat(db.count("IdHashChild")).isEqualTo(1);
|
||||
}
|
||||
|
||||
try (Db db = Db.open(Department.class, Employee.class)) {
|
||||
boolean[] removed = new boolean[1];
|
||||
List<String> sql = Db.sql(() -> db.txv(s -> {
|
||||
Department d = new Department("d");
|
||||
Employee e = new Employee("e");
|
||||
d.addEmployee(e);
|
||||
s.persist(d);
|
||||
removed[0] = d.getEmployees().remove(e);
|
||||
e.setDepartment(null);
|
||||
s.flush();
|
||||
}));
|
||||
t.line("UUID-based hashCode: Set.remove(child) returned " + removed[0]);
|
||||
t.step("commit", sql);
|
||||
t.line("rows left in employees: " + db.count("employees"));
|
||||
assertThat(removed[0]).isTrue();
|
||||
assertThat(db.count("employees")).isZero();
|
||||
}
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.ankurm.onetomany;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Collects what a test observed and writes output/NN-name-<label>.txt (label = h7 or h8); the tests assert the same facts. */
|
||||
final class Transcript {
|
||||
|
||||
static final String LABEL = System.getProperty("h.label", "h7");
|
||||
static final String VERSION = System.getProperty("h.version", "?");
|
||||
|
||||
private final List<String> lines = new ArrayList<>();
|
||||
private final Path file;
|
||||
|
||||
Transcript(String name, String title) {
|
||||
this.file = Path.of("output", name + "-" + LABEL + ".txt");
|
||||
line("# " + title);
|
||||
line("# Hibernate ORM " + VERSION + ", H2, JDK " + Runtime.version().feature());
|
||||
}
|
||||
|
||||
Transcript line(String s) {
|
||||
lines.add(s);
|
||||
return this;
|
||||
}
|
||||
|
||||
Transcript heading(String s) {
|
||||
line("");
|
||||
return line("== " + s);
|
||||
}
|
||||
|
||||
/** A step: the label, then every SQL statement Hibernate prepared during it. */
|
||||
Transcript step(String label, List<String> sql) {
|
||||
line("-- " + label);
|
||||
if (sql.isEmpty()) {
|
||||
line(" (no SQL)");
|
||||
}
|
||||
for (String s : sql) {
|
||||
line(" sql> " + s);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
void write() {
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, lines);
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user