From eab5461d860ae35f8fc1dc9371d9d562781451e1 Mon Sep 17 00:00:00 2001 From: asmhatre Date: Mon, 16 Nov 2026 10:49:49 +0530 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_017ic4b4H5ph3J7k2MJnRuVH --- README.md | 1 + one-to-many/README.md | 34 ++ one-to-many/output/01-shapes-h7.txt | 27 ++ one-to-many/output/02-bag-vs-set-h7.txt | 59 +++ one-to-many/output/03-sync-helper-h7.txt | 5 + one-to-many/output/04-fetch-defaults-h7.txt | 6 + one-to-many/output/05-n-plus-one-h7.txt | 15 + one-to-many/output/06-multiple-bag-h7.txt | 27 ++ one-to-many/output/07-id-hashcode-h7.txt | 13 + one-to-many/pom.xml | 67 ++++ one-to-many/scripts/run-all.sh | 7 + .../java/com/ankurm/onetomany/Department.java | 60 ++++ .../com/ankurm/onetomany/EagerDepartment.java | 39 ++ .../com/ankurm/onetomany/EagerEmployee.java | 36 ++ .../java/com/ankurm/onetomany/Employee.java | 67 ++++ .../java/com/ankurm/onetomany/Variants.java | 340 ++++++++++++++++++ .../test/java/com/ankurm/onetomany/Db.java | 171 +++++++++ .../com/ankurm/onetomany/T01_ShapesTest.java | 63 ++++ .../ankurm/onetomany/T02_BagVsSetTest.java | 164 +++++++++ .../ankurm/onetomany/T03_SyncHelperTest.java | 43 +++ .../com/ankurm/onetomany/T04_FetchTest.java | 93 +++++ .../ankurm/onetomany/T05_MultipleBagTest.java | 114 ++++++ .../ankurm/onetomany/T06_IdHashCodeTest.java | 54 +++ .../java/com/ankurm/onetomany/Transcript.java | 55 +++ 24 files changed, 1560 insertions(+) create mode 100644 one-to-many/README.md create mode 100644 one-to-many/output/01-shapes-h7.txt create mode 100644 one-to-many/output/02-bag-vs-set-h7.txt create mode 100644 one-to-many/output/03-sync-helper-h7.txt create mode 100644 one-to-many/output/04-fetch-defaults-h7.txt create mode 100644 one-to-many/output/05-n-plus-one-h7.txt create mode 100644 one-to-many/output/06-multiple-bag-h7.txt create mode 100644 one-to-many/output/07-id-hashcode-h7.txt create mode 100644 one-to-many/pom.xml create mode 100755 one-to-many/scripts/run-all.sh create mode 100644 one-to-many/src/main/java/com/ankurm/onetomany/Department.java create mode 100644 one-to-many/src/main/java/com/ankurm/onetomany/EagerDepartment.java create mode 100644 one-to-many/src/main/java/com/ankurm/onetomany/EagerEmployee.java create mode 100644 one-to-many/src/main/java/com/ankurm/onetomany/Employee.java create mode 100644 one-to-many/src/main/java/com/ankurm/onetomany/Variants.java create mode 100644 one-to-many/src/test/java/com/ankurm/onetomany/Db.java create mode 100644 one-to-many/src/test/java/com/ankurm/onetomany/T01_ShapesTest.java create mode 100644 one-to-many/src/test/java/com/ankurm/onetomany/T02_BagVsSetTest.java create mode 100644 one-to-many/src/test/java/com/ankurm/onetomany/T03_SyncHelperTest.java create mode 100644 one-to-many/src/test/java/com/ankurm/onetomany/T04_FetchTest.java create mode 100644 one-to-many/src/test/java/com/ankurm/onetomany/T05_MultipleBagTest.java create mode 100644 one-to-many/src/test/java/com/ankurm/onetomany/T06_IdHashCodeTest.java create mode 100644 one-to-many/src/test/java/com/ankurm/onetomany/Transcript.java diff --git a/README.md b/README.md index 40d1745..adcda17 100755 --- a/README.md +++ b/README.md @@ -351,3 +351,4 @@ Modules with their own `pom.xml` that run plain Hibernate without the Spring Boo | [`multitenancy`](multitenancy/) | Hibernate 7 multi-tenancy on Spring Boot 4.1.2: `@TenantId` discriminator vs schema-per-tenant (shared pool with `search_path`, and pool per tenant), tenant from a JWT claim, the `search_path` leak and the no-tenant failure modes, on PostgreSQL 17 (Hibernate `7.4.14.Final`) | | [`json-columns`](json-columns/) | JSON columns in Hibernate 7.4: `@JdbcTypeCode(SqlTypes.JSON)` for Map / List / record / POJO / `@Embeddable`, `json` vs `jsonb` DDL, HQL JSON functions, native JSONB operators, GIN and expression indexes with `EXPLAIN`, dirty checking, Jackson 3 vs Jackson 2 `FormatMapper`, MySQL 8.0, on PostgreSQL 18 (Hibernate `7.4.14.Final`, Spring Boot `4.1.2`) | | [`cascade-types`](cascade-types/) | JPA cascade types and `orphanRemoval` in Hibernate 7: composition vs aggregation, `orphanRemoval` vs `CascadeType.REMOVE`, the `cascade = ALL` on `@ManyToOne` incident reproduced in three schemas, `@ManyToMany` / `@OneToOne` / `@ManyToOne` cases, the cost of cascading a 1,000-row delete, `@OnDelete`, and the same tests on Hibernate `8.0.0.CR1`; plain Hibernate on H2 (Hibernate `7.4.15.Final`) | +| [`one-to-many`](one-to-many/) | `@OneToMany` in Hibernate 7: unidirectional join table vs `@JoinColumn` vs bidirectional `mappedBy`, the SQL each sends, why removing one child from a join-table `List` deletes and re-inserts the rest (and why a `mappedBy` List does not), the bidirectional sync helper, fetch defaults, N+1 fixes, `MultipleBagFetchException` and its three fixes, and the id-based `hashCode` trap; plain Hibernate on H2 (Hibernate `7.4.16.Final`) | diff --git a/one-to-many/README.md b/one-to-many/README.md new file mode 100644 index 0000000..63282ff --- /dev/null +++ b/one-to-many/README.md @@ -0,0 +1,34 @@ +# one-to-many + +Companion module for the ankurm.com article **@OneToMany in Hibernate 7: Unidirectional vs Bidirectional, Set vs List and the SQL**. +Every SQL statement and count in the article comes from a test here; each test writes what it observed to `output/` and asserts the same facts. +Plain Hibernate on an in-memory H2: no Spring, no Docker. + +## Versions + +| Component | Version | Notes | +|---|---|---| +| Hibernate ORM | `7.4.16.Final` | newest 7.x GA in `maven-metadata.xml` on 2026-11-16 (`8.0.0.CR1` is listed after it but is not GA) | +| Jakarta Persistence | `3.2.0` | | +| H2 | `2.4.240` | in memory | +| JUnit / AssertJ | `6.0.3` / `3.27.7` | | +| Java | `25` (Temurin 25.0.5+8) | | + +## Run + +```bash +./scripts/run-all.sh # or: mvn clean test +``` + +## Tests and what they write + +| Test | Output | Question it answers | +|---|---|---| +| `T01_ShapesTest` | `output/01-shapes-h7.txt` | Which tables and which insert SQL do the three mapping shapes produce? | +| `T02_BagVsSetTest` | `output/02-bag-vs-set-h7.txt` | What does removing ONE child cost, per mapping, with 5 and with 50 children? | +| `T03_SyncHelperTest` | `output/03-sync-helper-h7.txt` | What does the database hold if only the parent side is updated? | +| `T04_FetchTest` | `output/04-fetch-defaults-h7.txt`, `output/05-n-plus-one-h7.txt` | What do the fetch defaults load, and how many statements do N+1 and its fixes send? | +| `T05_MultipleBagTest` | `output/06-multiple-bag-h7.txt` | When does `MultipleBagFetchException` fire, and what do the three fixes cost? | +| `T06_IdHashCodeTest` | `output/07-id-hashcode-h7.txt` | Why does an id-based `hashCode` break `Set.remove()` after `persist()`? | + +Entities: `Department` / `Employee` are the recommended shape; [`Variants`](src/main/java/com/ankurm/onetomany/Variants.java) holds every other mapping as small nested entities (public fields, so the mapping is all there is to read); `EagerDepartment` / `EagerEmployee` leave the fetch defaults untouched. diff --git a/one-to-many/output/01-shapes-h7.txt b/one-to-many/output/01-shapes-h7.txt new file mode 100644 index 0000000..82eb21b --- /dev/null +++ b/one-to-many/output/01-shapes-h7.txt @@ -0,0 +1,27 @@ +# One parent, two children, four mappings: tables and insert SQL +# Hibernate ORM 7.4.16.Final, H2, JDK 25 + +== A. Unidirectional, plain @OneToMany (no mappedBy, no @JoinColumn) +tables: [JTCHILD, JTLISTPARENT, JTLISTPARENT_JTCHILD] +-- persist(parent with 2 children); commit + sql> insert into JtListParent (id) values (default) + sql> insert into JtChild (name,id) values (?,default) + sql> insert into JtChild (name,id) values (?,default) + sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?) + sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?) + +== B. Unidirectional with @JoinColumn(name = "parent_id") +tables: [JCCHILD, JCLISTPARENT] +-- persist(parent with 2 children); commit + sql> insert into JcListParent (id) values (default) + sql> insert into JcChild (name,id) values (?,default) + sql> insert into JcChild (name,id) values (?,default) + sql> update JcChild set parent_id=? where id=? + sql> update JcChild set parent_id=? where id=? + +== C. Bidirectional, mappedBy, child owns the foreign key +tables: [DEPARTMENTS, EMPLOYEES] +-- persist(department with 2 employees); commit + sql> insert into departments (name,id) values (?,default) + sql> insert into employees (dept_id,name,uuid,id) values (?,?,?,default) + sql> insert into employees (dept_id,name,uuid,id) values (?,?,?,default) diff --git a/one-to-many/output/02-bag-vs-set-h7.txt b/one-to-many/output/02-bag-vs-set-h7.txt new file mode 100644 index 0000000..c289a66 --- /dev/null +++ b/one-to-many/output/02-bag-vs-set-h7.txt @@ -0,0 +1,59 @@ +# Removing ONE child: statements sent, per mapping +# Hibernate ORM 7.4.16.Final, H2, JDK 25 +Each row: mapping | children before | statements on remove(one) + flush() | of which DELETE | of which INSERT | of which UPDATE + +== 5 children +join table, List (bag) | 5 | writes= 6 | delete=2 insert=4 update=0 +-- join table, List, n=5 + sql> select jlp1_0.id from JtListParent jlp1_0 where jlp1_0.id=? + sql> select c1_0.JtListParent_id,c1_1.id,c1_1.name from JtListParent_JtChild c1_0 join JtChild c1_1 on c1_1.id=c1_0.children_id where c1_0.JtListParent_id=? + sql> delete from JtListParent_JtChild where JtListParent_id=? + sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?) + sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?) + sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?) + sql> insert into JtListParent_JtChild (JtListParent_id,children_id) values (?,?) + sql> delete from JtChild where id=? +join table, Set | 5 | writes= 2 | delete=2 insert=0 update=0 +-- join table, Set, n=5 + sql> select jsp1_0.id from JtSetParent jsp1_0 where jsp1_0.id=? + sql> select c1_0.JtSetParent_id,c1_1.id,c1_1.name from JtSetParent_JtChild c1_0 join JtChild c1_1 on c1_1.id=c1_0.children_id where c1_0.JtSetParent_id=? + sql> delete from JtSetParent_JtChild where JtSetParent_id=? and children_id=? + sql> delete from JtChild where id=? +@JoinColumn, List (bag) | 5 | writes= 2 | delete=1 insert=0 update=1 +-- @JoinColumn, List, n=5 + sql> select jlp1_0.id from JcListParent jlp1_0 where jlp1_0.id=? + sql> select c1_0.parent_id,c1_0.id,c1_0.name from JcChild c1_0 where c1_0.parent_id=? + sql> update JcChild set parent_id=null where parent_id=? and id=? + sql> delete from JcChild where id=? +@JoinColumn + @OrderColumn, remove FIRST | 5 | writes= 10 | delete=1 insert=0 update=9 +-- @OrderColumn, remove first, n=5 + sql> select op1_0.id from OcParent op1_0 where op1_0.id=? + sql> select c1_0.parent_id,c1_0.pos,c1_0.id,c1_0.name from OcChild c1_0 where c1_0.parent_id=? + sql> update OcChild set parent_id=null,pos=null where parent_id=? and id=? + sql> update OcChild set parent_id=null,pos=null where parent_id=? and id=? + sql> update OcChild set parent_id=null,pos=null where parent_id=? and id=? + sql> update OcChild set parent_id=null,pos=null where parent_id=? and id=? + sql> update OcChild set parent_id=null,pos=null where parent_id=? and id=? + sql> update OcChild set parent_id=?,pos=? where id=? + sql> update OcChild set parent_id=?,pos=? where id=? + sql> update OcChild set parent_id=?,pos=? where id=? + sql> update OcChild set parent_id=?,pos=? where id=? + sql> delete from OcChild where id=? +bidirectional mappedBy, List (bag) | 5 | writes= 1 | delete=1 insert=0 update=0 +-- bidirectional, List, n=5 + sql> select bld1_0.id from BiListDept bld1_0 where bld1_0.id=? + sql> select e1_0.dept_id,e1_0.id,e1_0.name from BiListEmp e1_0 where e1_0.dept_id=? + sql> delete from BiListEmp where id=? +bidirectional mappedBy, Set | 5 | writes= 1 | delete=1 insert=0 update=0 +-- bidirectional, Set, n=5 + sql> select d1_0.id,d1_0.name from departments d1_0 where d1_0.id=? + sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? + sql> delete from employees where id=? + +== 50 children +join table, List (bag) | 50 | writes= 51 | delete=2 insert=49 update=0 +join table, Set | 50 | writes= 2 | delete=2 insert=0 update=0 +@JoinColumn, List (bag) | 50 | writes= 2 | delete=1 insert=0 update=1 +@JoinColumn + @OrderColumn, remove FIRST | 50 | writes=100 | delete=1 insert=0 update=99 +bidirectional mappedBy, List (bag) | 50 | writes= 1 | delete=1 insert=0 update=0 +bidirectional mappedBy, Set | 50 | writes= 1 | delete=1 insert=0 update=0 diff --git a/one-to-many/output/03-sync-helper-h7.txt b/one-to-many/output/03-sync-helper-h7.txt new file mode 100644 index 0000000..f8d2369 --- /dev/null +++ b/one-to-many/output/03-sync-helper-h7.txt @@ -0,0 +1,5 @@ +# Bidirectional sync: parent side only vs helper method +# Hibernate ORM 7.4.16.Final, H2, JDK 25 +in memory, before flush: e.department == null +database after commit: employee 1 has dept_id = null +database after commit: employee 2 (via helper) has dept_id = 2 diff --git a/one-to-many/output/04-fetch-defaults-h7.txt b/one-to-many/output/04-fetch-defaults-h7.txt new file mode 100644 index 0000000..99d386a --- /dev/null +++ b/one-to-many/output/04-fetch-defaults-h7.txt @@ -0,0 +1,6 @@ +# JPA fetch defaults: @OneToMany is LAZY, @ManyToOne is EAGER +# Hibernate ORM 7.4.16.Final, H2, JDK 25 +-- find(EagerEmployee) with @ManyToOne at its default + sql> select ee1_0.id,d1_0.id,d1_0.name,ee1_0.name from EagerEmployee ee1_0 left join EagerDepartment d1_0 on d1_0.id=ee1_0.dept_id where ee1_0.id=? +-- find(EagerDepartment): the @OneToMany collection is not loaded + sql> select ed1_0.id,ed1_0.name from EagerDepartment ed1_0 where ed1_0.id=? diff --git a/one-to-many/output/05-n-plus-one-h7.txt b/one-to-many/output/05-n-plus-one-h7.txt new file mode 100644 index 0000000..a9d4e07 --- /dev/null +++ b/one-to-many/output/05-n-plus-one-h7.txt @@ -0,0 +1,15 @@ +# N+1 and its fixes: statements sent for 5 departments with 3 employees each +# Hibernate ORM 7.4.16.Final, H2, JDK 25 +-- naive: query departments, then touch each employees collection + sql> select d1_0.id,d1_0.name from departments d1_0 + sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? + sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? + sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? + sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? + sql> select e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid from employees e1_0 where e1_0.dept_id=? + departments returned: 5 (no DISTINCT needed in Hibernate 7) +-- fix 1: left join fetch d.employees + sql> select d1_0.id,e1_0.dept_id,e1_0.id,e1_0.name,e1_0.uuid,d1_0.name from departments d1_0 left join employees e1_0 on d1_0.id=e1_0.dept_id +-- fix 2: @BatchSize(size = 20) on the collection, same loop as the naive one + sql> select bd1_0.id from BatchDept bd1_0 + sql> select e1_0.dept_id,e1_0.id,e1_0.name from BatchEmp e1_0 where e1_0.dept_id in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) diff --git a/one-to-many/output/06-multiple-bag-h7.txt b/one-to-many/output/06-multiple-bag-h7.txt new file mode 100644 index 0000000..89fd65d --- /dev/null +++ b/one-to-many/output/06-multiple-bag-h7.txt @@ -0,0 +1,27 @@ +# MultipleBagFetchException and three fixes (3 employees, 4 projects per department) +# Hibernate ORM 7.4.16.Final, H2, JDK 25 + +== The failure: two Lists, two join fetches +exception: java.lang.IllegalArgumentException <- org.hibernate.loader.MultipleBagFetchException +message: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [com.ankurm.onetomany.Variants$BagDept.employees, com.ankurm.onetomany.Variants$BagDept.projects] +-- SQL sent before the exception + (no SQL) + +== Fix 2: split into two queries (same Lists) + employees=3 projects=4 +-- two queries, one collection each + sql> select bd1_0.id,e1_0.dept_id,e1_0.id,e1_0.name from BagDept bd1_0 left join BagEmp e1_0 on bd1_0.id=e1_0.dept_id + sql> select bd1_0.id,p1_0.dept_id,p1_0.id,p1_0.title from BagDept bd1_0 left join BagProject p1_0 on bd1_0.id=p1_0.dept_id where bd1_0.id in (?) + +== Fix 1: Set instead of List + employees=3 projects=4 +-- one query, two join fetches + sql> select sd1_0.id,e1_0.dept_id,e1_0.id,e1_0.name,p1_0.dept_id,p1_0.id,p1_0.title from SetDept sd1_0 left join SetEmp e1_0 on sd1_0.id=e1_0.dept_id left join SetProject p1_0 on sd1_0.id=p1_0.dept_id +rows the database returned for that one query: 12 (3 x 4: the Cartesian product Hibernate then folds back into 3 + 4 objects) + +== Fix 3: keep Lists, drop the join fetch, add @BatchSize + employees=3 projects=4 +-- query the parents, touch both collections + sql> select bd1_0.id from BatchDept bd1_0 + sql> select e1_0.dept_id,e1_0.id,e1_0.name from BatchEmp e1_0 where e1_0.dept_id=? + sql> select p1_0.dept_id,p1_0.id,p1_0.title from BatchProject p1_0 where p1_0.dept_id=? diff --git a/one-to-many/output/07-id-hashcode-h7.txt b/one-to-many/output/07-id-hashcode-h7.txt new file mode 100644 index 0000000..e2172e3 --- /dev/null +++ b/one-to-many/output/07-id-hashcode-h7.txt @@ -0,0 +1,13 @@ +# Set + id-based hashCode vs UUID-based hashCode: remove() after persist +# Hibernate ORM 7.4.16.Final, H2, JDK 25 +id-based hashCode: Set.remove(child) returned false +-- commit + sql> insert into IdHashOwner (id) values (default) + sql> insert into IdHashChild (name,owner_id,id) values (?,?,default) +rows left in IdHashChild: 1 (the child was NOT removed, so orphanRemoval never saw it) +UUID-based hashCode: Set.remove(child) returned true +-- commit + sql> insert into departments (name,id) values (?,default) + sql> insert into employees (dept_id,name,uuid,id) values (?,?,?,default) + sql> delete from employees where id=? +rows left in employees: 0 diff --git a/one-to-many/pom.xml b/one-to-many/pom.xml new file mode 100644 index 0000000..0812e72 --- /dev/null +++ b/one-to-many/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + com.ankurm + one-to-many + 1.0.0 + one-to-many + @OneToMany in Hibernate 7: unidirectional vs bidirectional, Set vs List, the SQL each variant sends, MultipleBagFetchException and its fixes (plain Hibernate on H2) + + + 25 + UTF-8 + + 7.4.16.Final + 3.2.0 + h7 + + + + + org.hibernate.orm + hibernate-core + ${hibernate.version} + + + jakarta.persistence + jakarta.persistence-api + ${persistence.version} + + + com.h2database + h2 + 2.4.240 + + + org.junit.jupiter + junit-jupiter + 6.0.3 + test + + + org.assertj + assertj-core + 3.27.7 + test + + + + + + + maven-surefire-plugin + 3.6.0 + + -Xmx512m + + ${h.label} + ${hibernate.version} + + + + + + diff --git a/one-to-many/scripts/run-all.sh b/one-to-many/scripts/run-all.sh new file mode 100755 index 0000000..c17c31a --- /dev/null +++ b/one-to-many/scripts/run-all.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Regenerates every file under output/. Needs JDK 25, Maven 3.9 and network access to Maven Central (no Docker: H2 only). +# ./scripts/run-all.sh +set -euo pipefail +cd "$(dirname "$0")/.." +mvn -B clean test +ls -1 output diff --git a/one-to-many/src/main/java/com/ankurm/onetomany/Department.java b/one-to-many/src/main/java/com/ankurm/onetomany/Department.java new file mode 100644 index 0000000..73c30be --- /dev/null +++ b/one-to-many/src/main/java/com/ankurm/onetomany/Department.java @@ -0,0 +1,60 @@ +package com.ankurm.onetomany; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import java.util.HashSet; +import java.util.Set; + +/** The recommended shape: bidirectional, child owns the foreign key, a Set, helper methods on the parent. */ +@Entity +@Table(name = "departments") +public class Department { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String name; + + // mappedBy = "department" names the field on Employee that owns the foreign key column. + @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) + private Set employees = new HashSet<>(); + + protected Department() { + } + + public Department(String name) { + this.name = name; + } + + // The invariant that keeps both sides of the association in step. + public void addEmployee(Employee employee) { + employees.add(employee); + employee.setDepartment(this); + } + + public void removeEmployee(Employee employee) { + employees.remove(employee); + employee.setDepartment(null); + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public Set getEmployees() { + return employees; + } +} diff --git a/one-to-many/src/main/java/com/ankurm/onetomany/EagerDepartment.java b/one-to-many/src/main/java/com/ankurm/onetomany/EagerDepartment.java new file mode 100644 index 0000000..6393112 --- /dev/null +++ b/one-to-many/src/main/java/com/ankurm/onetomany/EagerDepartment.java @@ -0,0 +1,39 @@ +package com.ankurm.onetomany; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +/** The one-to-many side with no fetch attribute: JPA's default for @OneToMany is LAZY. */ +@Entity +public class EagerDepartment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + + @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) + private List employees = new ArrayList<>(); + + protected EagerDepartment() { + } + + public EagerDepartment(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public List getEmployees() { + return employees; + } +} diff --git a/one-to-many/src/main/java/com/ankurm/onetomany/EagerEmployee.java b/one-to-many/src/main/java/com/ankurm/onetomany/EagerEmployee.java new file mode 100644 index 0000000..aeb3875 --- /dev/null +++ b/one-to-many/src/main/java/com/ankurm/onetomany/EagerEmployee.java @@ -0,0 +1,36 @@ +package com.ankurm.onetomany; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; + +/** A child that leaves @ManyToOne at its default, to show what the default loads. */ +@Entity +public class EagerEmployee { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + + // No fetch attribute: JPA's default for @ManyToOne is EAGER. + @ManyToOne + @JoinColumn(name = "dept_id") + private EagerDepartment department; + + protected EagerEmployee() { + } + + public EagerEmployee(String name, EagerDepartment department) { + this.name = name; + this.department = department; + } + + public Long getId() { + return id; + } +} diff --git a/one-to-many/src/main/java/com/ankurm/onetomany/Employee.java b/one-to-many/src/main/java/com/ankurm/onetomany/Employee.java new file mode 100644 index 0000000..14e7e64 --- /dev/null +++ b/one-to-many/src/main/java/com/ankurm/onetomany/Employee.java @@ -0,0 +1,67 @@ +package com.ankurm.onetomany; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.util.Objects; +import java.util.UUID; + +/** The owning side. equals/hashCode use a UUID assigned at construction, so they stay stable from new() to persist() to detach. */ +@Entity +@Table(name = "employees") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String name; + + @Column(nullable = false, updatable = false) + private UUID uuid = UUID.randomUUID(); + + // LAZY: the JPA default for @ManyToOne is EAGER; this line is what opts out. + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "dept_id") + private Department department; + + protected Employee() { + } + + public Employee(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + @Override + public boolean equals(Object o) { + return o instanceof Employee e && Objects.equals(uuid, e.uuid); + } + + @Override + public int hashCode() { + return Objects.hashCode(uuid); + } +} diff --git a/one-to-many/src/main/java/com/ankurm/onetomany/Variants.java b/one-to-many/src/main/java/com/ankurm/onetomany/Variants.java new file mode 100644 index 0000000..dabcf36 --- /dev/null +++ b/one-to-many/src/main/java/com/ankurm/onetomany/Variants.java @@ -0,0 +1,340 @@ +package com.ankurm.onetomany; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OrderColumn; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.hibernate.annotations.BatchSize; + +/** + * Every other @OneToMany shape the article compares, as small entities with public fields so the mapping is the only thing to read. + * Naming: Jt = unidirectional join table, Jc = unidirectional @JoinColumn, Bi = bidirectional, Oc = @OrderColumn. + */ +public final class Variants { + + private Variants() { + } + + // ---- unidirectional, no mappedBy, no @JoinColumn: Hibernate adds a join table ---- + + @Entity(name = "JtChild") + public static class JtChild { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String name; + + protected JtChild() { + } + + public JtChild(String name) { + this.name = name; + } + } + + @Entity(name = "JtListParent") + public static class JtListParent { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + public List children = new ArrayList<>(); + } + + @Entity(name = "JtSetParent") + public static class JtSetParent { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + public Set children = new HashSet<>(); + } + + // ---- unidirectional with @JoinColumn: no join table, the child table carries the foreign key ---- + + @Entity(name = "JcChild") + public static class JcChild { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String name; + + protected JcChild() { + } + + public JcChild(String name) { + this.name = name; + } + } + + @Entity(name = "JcListParent") + public static class JcListParent { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + @JoinColumn(name = "parent_id") + public List children = new ArrayList<>(); + } + + // ---- unidirectional @JoinColumn plus @OrderColumn: the list keeps a position column ---- + + @Entity(name = "OcChild") + public static class OcChild { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String name; + + protected OcChild() { + } + + public OcChild(String name) { + this.name = name; + } + } + + @Entity(name = "OcParent") + public static class OcParent { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + @JoinColumn(name = "parent_id") + @OrderColumn(name = "pos") + public List children = new ArrayList<>(); + } + + // ---- bidirectional with a List (a "bag"): the owning side is the child ---- + + @Entity(name = "BiListEmp") + public static class BiListEmp { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String name; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "dept_id") + public BiListDept department; + + protected BiListEmp() { + } + + public BiListEmp(String name) { + this.name = name; + } + } + + @Entity(name = "BiListDept") + public static class BiListDept { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true) + public List employees = new ArrayList<>(); + + public void add(BiListEmp e) { + employees.add(e); + e.department = this; + } + } + + // ---- two collections on one parent, three ways: bags, sets, bags with @BatchSize ---- + + @Entity(name = "BagEmp") + public static class BagEmp { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String name; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "dept_id") + public BagDept department; + + protected BagEmp() { + } + + public BagEmp(String name) { + this.name = name; + } + } + + @Entity(name = "BagProject") + public static class BagProject { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String title; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "dept_id") + public BagDept department; + + protected BagProject() { + } + + public BagProject(String title) { + this.title = title; + } + } + + @Entity(name = "BagDept") + public static class BagDept { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) + public List employees = new ArrayList<>(); + @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) + public List projects = new ArrayList<>(); + } + + @Entity(name = "SetEmp") + public static class SetEmp { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String name; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "dept_id") + public SetDept department; + + protected SetEmp() { + } + + public SetEmp(String name) { + this.name = name; + } + } + + @Entity(name = "SetProject") + public static class SetProject { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String title; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "dept_id") + public SetDept department; + + protected SetProject() { + } + + public SetProject(String title) { + this.title = title; + } + } + + @Entity(name = "SetDept") + public static class SetDept { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) + public Set employees = new HashSet<>(); + @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) + public Set projects = new HashSet<>(); + } + + @Entity(name = "BatchEmp") + public static class BatchEmp { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String name; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "dept_id") + public BatchDept department; + + protected BatchEmp() { + } + + public BatchEmp(String name) { + this.name = name; + } + } + + @Entity(name = "BatchProject") + public static class BatchProject { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String title; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "dept_id") + public BatchDept department; + + protected BatchProject() { + } + + public BatchProject(String title) { + this.title = title; + } + } + + @Entity(name = "BatchDept") + public static class BatchDept { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) + @BatchSize(size = 20) + public List employees = new ArrayList<>(); + @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) + @BatchSize(size = 20) + public List projects = new ArrayList<>(); + } + + // ---- an id-based hashCode on a child inside a Set ---- + + @Entity(name = "IdHashChild") + public static class IdHashChild { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + public String name; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "owner_id") + public IdHashOwner owner; + + protected IdHashChild() { + } + + public IdHashChild(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + return o instanceof IdHashChild c && java.util.Objects.equals(id, c.id); + } + + @Override + public int hashCode() { + return java.util.Objects.hashCode(id); // BUG on purpose: id is null until persist + } + } + + @Entity(name = "IdHashOwner") + public static class IdHashOwner { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long id; + @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL, orphanRemoval = true) + public Set children = new HashSet<>(); + + public void add(IdHashChild c) { + children.add(c); + c.owner = this; + } + } +} diff --git a/one-to-many/src/test/java/com/ankurm/onetomany/Db.java b/one-to-many/src/test/java/com/ankurm/onetomany/Db.java new file mode 100644 index 0000000..12cbbc1 --- /dev/null +++ b/one-to-many/src/test/java/com/ankurm/onetomany/Db.java @@ -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 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 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 tx(Function 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 work) { + tx(s -> { + work.accept(s); + return null; + }); + } + + /** Runs the action and returns the SQL Hibernate prepared while it ran. */ + static List 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 rows(String sql) { + return tx(s -> s.doReturningWork(cn -> { + List 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 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(); + } + } +} diff --git a/one-to-many/src/test/java/com/ankurm/onetomany/T01_ShapesTest.java b/one-to-many/src/test/java/com/ankurm/onetomany/T01_ShapesTest.java new file mode 100644 index 0000000..540418e --- /dev/null +++ b/one-to-many/src/test/java/com/ankurm/onetomany/T01_ShapesTest.java @@ -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 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 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 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 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(); + } +} diff --git a/one-to-many/src/test/java/com/ankurm/onetomany/T02_BagVsSetTest.java b/one-to-many/src/test/java/com/ankurm/onetomany/T02_BagVsSetTest.java new file mode 100644 index 0000000..243e487 --- /dev/null +++ b/one-to-many/src/test/java/com/ankurm/onetomany/T02_BagVsSetTest.java @@ -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 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 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 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 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 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 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 sql, String verb) { + return sql.stream().filter(s -> s.toLowerCase().startsWith(verb)).count(); + } + + private static void row(Transcript t, String mapping, int n, List 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"))); + } +} diff --git a/one-to-many/src/test/java/com/ankurm/onetomany/T03_SyncHelperTest.java b/one-to-many/src/test/java/com/ankurm/onetomany/T03_SyncHelperTest.java new file mode 100644 index 0000000..edac5a8 --- /dev/null +++ b/one-to-many/src/test/java/com/ankurm/onetomany/T03_SyncHelperTest.java @@ -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(); + } +} diff --git a/one-to-many/src/test/java/com/ankurm/onetomany/T04_FetchTest.java b/one-to-many/src/test/java/com/ankurm/onetomany/T04_FetchTest.java new file mode 100644 index 0000000..21a647e --- /dev/null +++ b/one-to-many/src/test/java/com/ankurm/onetomany/T04_FetchTest.java @@ -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 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 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 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 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(); + } +} diff --git a/one-to-many/src/test/java/com/ankurm/onetomany/T05_MultipleBagTest.java b/one-to-many/src/test/java/com/ankurm/onetomany/T05_MultipleBagTest.java new file mode 100644 index 0000000..eb3559a --- /dev/null +++ b/one-to-many/src/test/java/com/ankurm/onetomany/T05_MultipleBagTest.java @@ -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 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 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 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 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(); + } +} diff --git a/one-to-many/src/test/java/com/ankurm/onetomany/T06_IdHashCodeTest.java b/one-to-many/src/test/java/com/ankurm/onetomany/T06_IdHashCodeTest.java new file mode 100644 index 0000000..df26d3e --- /dev/null +++ b/one-to-many/src/test/java/com/ankurm/onetomany/T06_IdHashCodeTest.java @@ -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 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 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(); + } +} diff --git a/one-to-many/src/test/java/com/ankurm/onetomany/Transcript.java b/one-to-many/src/test/java/com/ankurm/onetomany/Transcript.java new file mode 100644 index 0000000..f1070ad --- /dev/null +++ b/one-to-many/src/test/java/com/ankurm/onetomany/Transcript.java @@ -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-