From 4c795e8b5038ebb6f2702931534209399522cee6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:11:39 +0530 Subject: [PATCH] Add embeddables module: @Embeddable records in Hibernate 7.4.17.Final (columns and round trip, null handling, collections of embeddables and their SQL, record equality vs database equality, @EmbeddedId records, DDD Email value object, failure modes; H2) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017ic4b3obqqePfZ9m2Jk5Ub --- README.md | 1 + embeddables/README.md | 38 +++++ embeddables/output/01-basic.txt | 36 +++++ embeddables/output/02-two-uses.txt | 20 +++ embeddables/output/03-nulls.txt | 47 ++++++ embeddables/output/04-primitives.txt | 14 ++ embeddables/output/05-collections.txt | 93 ++++++++++++ embeddables/output/06-collection-nulls.txt | 31 ++++ embeddables/output/07-equality.txt | 32 ++++ embeddables/output/08-value-object.txt | 29 ++++ embeddables/output/09-failures.txt | 33 +++++ embeddables/output/10-setting-search.txt | 5 + embeddables/pom.xml | 65 ++++++++ embeddables/scripts/run-all.sh | 8 + embeddables/scripts/search-setting.sh | 19 +++ .../java/com/ankurm/embeddables/Account.java | 14 ++ .../java/com/ankurm/embeddables/Address.java | 7 + .../java/com/ankurm/embeddables/Article.java | 39 +++++ .../com/ankurm/embeddables/BadCustomer.java | 17 +++ .../main/java/com/ankurm/embeddables/Box.java | 23 +++ .../java/com/ankurm/embeddables/Customer.java | 38 +++++ .../main/java/com/ankurm/embeddables/Dim.java | 8 + .../java/com/ankurm/embeddables/Email.java | 21 +++ .../main/java/com/ankurm/embeddables/Geo.java | 8 + .../java/com/ankurm/embeddables/Handle.java | 8 + .../java/com/ankurm/embeddables/Holder.java | 15 ++ .../java/com/ankurm/embeddables/Member.java | 22 +++ .../java/com/ankurm/embeddables/Money.java | 12 ++ .../java/com/ankurm/embeddables/NnTag.java | 11 ++ .../com/ankurm/embeddables/OrderLine.java | 20 +++ .../com/ankurm/embeddables/OrderLineId.java | 8 + .../java/com/ankurm/embeddables/Parcel.java | 22 +++ .../com/ankurm/embeddables/PlainMoney.java | 5 + .../java/com/ankurm/embeddables/Product.java | 25 ++++ .../com/ankurm/embeddables/RecordEntity.java | 9 ++ .../main/java/com/ankurm/embeddables/Tag.java | 7 + .../java/com/ankurm/embeddables/Weight.java | 15 ++ .../test/java/com/ankurm/embeddables/Db.java | 140 ++++++++++++++++++ .../com/ankurm/embeddables/T01_BasicTest.java | 77 ++++++++++ .../com/ankurm/embeddables/T02_NullTest.java | 88 +++++++++++ .../embeddables/T03_CollectionTest.java | 89 +++++++++++ .../ankurm/embeddables/T04_EqualityTest.java | 56 +++++++ .../embeddables/T05_ValueObjectTest.java | 37 +++++ .../ankurm/embeddables/T06_FailuresTest.java | 80 ++++++++++ .../com/ankurm/embeddables/Transcript.java | 61 ++++++++ 45 files changed, 1453 insertions(+) create mode 100644 embeddables/README.md create mode 100644 embeddables/output/01-basic.txt create mode 100644 embeddables/output/02-two-uses.txt create mode 100644 embeddables/output/03-nulls.txt create mode 100644 embeddables/output/04-primitives.txt create mode 100644 embeddables/output/05-collections.txt create mode 100644 embeddables/output/06-collection-nulls.txt create mode 100644 embeddables/output/07-equality.txt create mode 100644 embeddables/output/08-value-object.txt create mode 100644 embeddables/output/09-failures.txt create mode 100644 embeddables/output/10-setting-search.txt create mode 100644 embeddables/pom.xml create mode 100755 embeddables/scripts/run-all.sh create mode 100755 embeddables/scripts/search-setting.sh create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Account.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Address.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Article.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/BadCustomer.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Box.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Customer.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Dim.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Email.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Geo.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Handle.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Holder.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Member.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Money.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/NnTag.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/OrderLine.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/OrderLineId.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Parcel.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/PlainMoney.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Product.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/RecordEntity.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Tag.java create mode 100644 embeddables/src/main/java/com/ankurm/embeddables/Weight.java create mode 100644 embeddables/src/test/java/com/ankurm/embeddables/Db.java create mode 100644 embeddables/src/test/java/com/ankurm/embeddables/T01_BasicTest.java create mode 100644 embeddables/src/test/java/com/ankurm/embeddables/T02_NullTest.java create mode 100644 embeddables/src/test/java/com/ankurm/embeddables/T03_CollectionTest.java create mode 100644 embeddables/src/test/java/com/ankurm/embeddables/T04_EqualityTest.java create mode 100644 embeddables/src/test/java/com/ankurm/embeddables/T05_ValueObjectTest.java create mode 100644 embeddables/src/test/java/com/ankurm/embeddables/T06_FailuresTest.java create mode 100644 embeddables/src/test/java/com/ankurm/embeddables/Transcript.java diff --git a/README.md b/README.md index 6c4aa56..096dfaa 100755 --- a/README.md +++ b/README.md @@ -355,3 +355,4 @@ Modules with their own `pom.xml` that run plain Hibernate without the Spring Boo | [`n-plus-one-guard`](n-plus-one-guard/) | Detecting N+1 queries automatically: Hibernate Statistics vs datasource-proxy (what each counts and what each misses), five fixes with statement counts, and a JUnit 6 `@MaxSelects` guard that fails a test with the full SQL list; plain Hibernate on H2 (Hibernate `7.4.16.Final`, datasource-proxy `1.11.1`) | | [`enums`](enums/) | Enum mapping in Hibernate 7: `ORDINAL` vs `STRING` vs PostgreSQL native enum vs `AttributeConverter` vs JPA 3.2 `@EnumeratedValue`, the DDL each creates, what release 2 reads and writes after a constant is inserted, appended or renamed, `hbm2ddl=update` limits and the migration each change needs; plain Hibernate on H2 and PostgreSQL 18 (Hibernate `7.4.17.Final`) | | [`formula-filter`](formula-filter/) | `@Formula`, `@Filter` and `@SQLRestriction` in Hibernate 7: the SQL each one adds, `@Formula` staleness and the unqualified-column trap, where filters skip find-by-id, collections and loaded collections, `applyToLoadByKey`, `autoEnabled` tenant filters, and the removed `@Where`; plain Hibernate on H2 (Hibernate `7.4.17.Final`) | +| [`embeddables`](embeddables/) | Records and value objects in Hibernate 7: `@Embeddable` records, null handling (all-null columns, partial nulls, compact constructors), collections of embeddables and the SQL for add/remove, record equality vs database equality, `@EmbeddedId` records, a DDD `Email` value object, and the failure modes; plain Hibernate on H2 (Hibernate `7.4.17.Final`) | diff --git a/embeddables/README.md b/embeddables/README.md new file mode 100644 index 0000000..daa1fc0 --- /dev/null +++ b/embeddables/README.md @@ -0,0 +1,38 @@ +# embeddables + +Companion module for the ankurm.com article **Records and Value Objects in Hibernate 7: @Embeddable Records Done Right**. +Every SQL statement, result and error message 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, no database server. + +## Versions + +| Component | Version | Notes | +|---|---|---| +| Hibernate ORM | `7.4.17.Final` | newest 7.x GA in `maven-metadata.xml` on 2026-11-26 (`8.0.0.CR2` is listed after it, but CR2 is not GA) | +| Jakarta Persistence | `3.2.0` | newest GA in `maven-metadata.xml` (`4.0.0-M8` is a milestone); also what `hibernate-core:7.4.17.Final`'s POM depends on | +| H2 | `2.4.240` | in memory | +| JUnit / AssertJ | `6.0.3` / `3.27.7` | | +| Java | `25` (Temurin 25.0.5.1 LTS) | | + +## Run + +```bash +./scripts/run-all.sh # mvn clean test, then the jar search; regenerates everything in output/ +``` + +## Tests and what they write + +| Test | Output | Question it answers | +|---|---|---| +| `T01_BasicTest.basic` | `output/01-basic.txt` | What does `@Embeddable record Money` map to, how does it round-trip, how is an update detected? | +| `T01_BasicTest.sameRecordTwice` | `output/02-two-uses.txt` | Same record twice in one entity (`@AttributeOverride`), nested record (`Geo` inside `Address`) | +| `T02_NullTest.nulls` | `output/03-nulls.txt` | All-null columns, partly-null columns, `is null` queries, a compact constructor that rejects nulls, the `create_empty_composites` setting | +| `T02_NullTest.primitivesAndNotNull` | `output/04-primitives.txt` | A record with `int` components as an optional embedded attribute | +| `T03_CollectionTest.collections` | `output/05-collections.txt` | `@ElementCollection` of records: Set vs List vs `@OrderColumn` vs Set with NOT NULL components, SQL for add and remove | +| `T03_CollectionTest.nullsInsideElements` | `output/06-collection-nulls.txt` | Null components and all-null elements in a collection | +| `T04_EqualityTest` | `output/07-equality.txt` | Record `equals` vs database equality, embeddables in HQL, record as `@EmbeddedId` | +| `T05_ValueObjectTest` | `output/08-value-object.txt` | `record Email(String value)`: normalisation, queries, invalid data already in the table | +| `T06_FailuresTest` | `output/09-failures.txt` | Duplicate columns, a component named `value`, a record without `@Embeddable`, a record as `@Entity` | +| `scripts/search-setting.sh` | `output/10-setting-search.txt` | Does `create_empty_composites` occur anywhere in the Hibernate 7.4.17 jar? | + +Entities and embeddables are in [`src/main/java/com/ankurm/embeddables`](src/main/java/com/ankurm/embeddables); `Db` and `Transcript` in `src/test` capture every SQL statement Hibernate prepares. diff --git a/embeddables/output/01-basic.txt b/embeddables/output/01-basic.txt new file mode 100644 index 0000000..b0de4a3 --- /dev/null +++ b/embeddables/output/01-basic.txt @@ -0,0 +1,36 @@ +# @Embeddable record Money(amount, currency) inside Product +# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25 + +== Columns of table product + AMOUNT | NUMERIC | null | 12 | 2 | YES + CURRENCY | CHARACTER VARYING | 3 | null | null | YES + ID | BIGINT | null | 64 | 0 | NO + NAME | CHARACTER VARYING | 255 | null | null | YES + +== Insert and load +-- persist Product(1, Keyboard, Money(10.5, INR)) + sql> insert into Product (name,amount,currency,id) values (?,?,?,?) + => persisted + in database: [10.50 | INR | 1 | Keyboard] +-- load Product 1 in a new session + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.id=? + => Money[amount=10.50, currency=INR] + in-memory Money(10.5, INR).equals(Money loaded back from NUMERIC(12,2)) = false + +== Updating: replace the whole record +-- replace price with Money(12.00, INR) + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.id=? + sql> update Product set name=?,amount=?,currency=? where id=? + => replaced +-- replace price with an equal-valued Money(12.0, INR) (scale 1 vs 2) + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.id=? + => replaced + record equals says: false + update issued: false +-- replace price with a really different Money(13.00, INR) + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.id=? + sql> update Product set name=?,amount=?,currency=? where id=? + => replaced +-- replace price with an identical new instance Money(13.00, INR) + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.id=? + => replaced diff --git a/embeddables/output/02-two-uses.txt b/embeddables/output/02-two-uses.txt new file mode 100644 index 0000000..26dc511 --- /dev/null +++ b/embeddables/output/02-two-uses.txt @@ -0,0 +1,20 @@ +# The same record type embedded twice (Address as billing and shipping), with a nested record (Geo) +# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25 + +== Columns of table customer + LAT | DOUBLE PRECISION | null | 53 | null | YES + LON | DOUBLE PRECISION | null | 53 | null | YES + SHIP_LAT | DOUBLE PRECISION | null | 53 | null | YES + SHIP_LON | DOUBLE PRECISION | null | 53 | null | YES + ID | BIGINT | null | 64 | 0 | NO + CITY | CHARACTER VARYING | 255 | null | null | YES + SHIP_CITY | CHARACTER VARYING | 255 | null | null | YES + SHIP_STREET | CHARACTER VARYING | 255 | null | null | YES + SHIP_ZIP | CHARACTER VARYING | 255 | null | null | YES + STREET | CHARACTER VARYING | 255 | null | null | YES + ZIP | CHARACTER VARYING | 255 | null | null | YES + +== Load it back +-- find Customer 1 + sql> select c1_0.id,c1_0.street,c1_0.city,c1_0.zip,c1_0.lat,c1_0.lon,c1_0.ship_street,c1_0.ship_city,c1_0.ship_zip,c1_0.ship_lat,c1_0.ship_lon from Customer c1_0 where c1_0.id=? + => billing=Address[street=1 MG Road, city=Pune, zip=411001, geo=Geo[lat=18.5, lon=73.8]] shipping=Address[street=9 Marine Dr, city=Mumbai, zip=400020, geo=null] diff --git a/embeddables/output/03-nulls.txt b/embeddables/output/03-nulls.txt new file mode 100644 index 0000000..d52ef80 --- /dev/null +++ b/embeddables/output/03-nulls.txt @@ -0,0 +1,47 @@ +# Null handling for record embeddables +# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25 + +== A null embedded attribute is written as all-null columns +-- persist Product(1, Mouse, price = null) + sql> insert into Product (name,amount,currency,id) values (?,?,?,?) + => persisted + in database: [1 | Mouse | null | null] +-- load it back + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.id=? + => null + +== Partly null columns give a record with null components +-- persist Money(null, INR), load it back + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.id=? + => Money[amount=null, currency=INR] + +== Querying for 'no price' +-- from Product p where p.price is null + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.amount is null and p1_0.currency is null + => [1] +-- from Product p where p.price.amount is null + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.amount is null + => [1, 2] + +== Nested embeddable: Address with all-null Geo inside a non-null Address +-- load Customer 1 (geo columns all null, shipping columns all null) + sql> select c1_0.id,c1_0.street,c1_0.city,c1_0.zip,c1_0.lat,c1_0.lon,c1_0.ship_street,c1_0.ship_city,c1_0.ship_zip,c1_0.ship_lat,c1_0.ship_lon from Customer c1_0 where c1_0.id=? + => billing=Address[street=1 MG Road, city=Pune, zip=411001, geo=null] shipping=null + +== A compact constructor that rejects nulls (Weight) +-- persist Parcel(1, null) and load it + sql> insert into Parcel (magnitude,unit,id) values (?,?,?) + sql> select p1_0.id,p1_0.magnitude,p1_0.unit from Parcel p1_0 where p1_0.id=? + => null +-- row with value null, unit 'kg': find Parcel 2 + sql> select p1_0.id,p1_0.magnitude,p1_0.unit from Parcel p1_0 where p1_0.id=? + => InstantiationException: Could not instantiate entity 'com.ankurm.embeddables.Weight' due to: null [root cause: NullPointerException: magnitude] + +== hibernate.create_empty_composites.enabled=true (a setting often cited online for this; see output/10-setting-search.txt) +-- Product with all-null price columns, load it (Money has no validation) + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where p1_0.id=? + => null + (same as the default above: the setting changed nothing) +-- Parcel with all-null weight columns, load it (Weight rejects nulls) + sql> select p1_0.id,p1_0.magnitude,p1_0.unit from Parcel p1_0 where p1_0.id=? + => null diff --git a/embeddables/output/04-primitives.txt b/embeddables/output/04-primitives.txt new file mode 100644 index 0000000..cefa85e --- /dev/null +++ b/embeddables/output/04-primitives.txt @@ -0,0 +1,14 @@ +# A record with primitive components (Dim(int width, int height)) as an optional embedded attribute +# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25 + +== Columns of table box + HEIGHT | INTEGER | null | 32 | 0 | YES + WIDTH | INTEGER | null | 32 | 0 | YES + ID | BIGINT | null | 64 | 0 | NO +-- persist Box(1, Dim(3, 4)) + sql> insert into Box (width,height,id) values (?,?,?) + => persisted +-- persist Box(2, null) + sql> insert into Box (width,height,id) values (?,?,?) + => persisted + rows: [4 | 3 | 1, null | null | 2] diff --git a/embeddables/output/05-collections.txt b/embeddables/output/05-collections.txt new file mode 100644 index 0000000..ddd6186 --- /dev/null +++ b/embeddables/output/05-collections.txt @@ -0,0 +1,93 @@ +# @ElementCollection of record Tag(name, colour): Set vs List (bag) vs List with @OrderColumn +# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25 + +== Columns of table article_tagset + ARTICLE_ID | BIGINT | null | 64 | 0 | NO + COLOUR | CHARACTER VARYING | 255 | null | null | YES + NAME | CHARACTER VARYING | 255 | null | null | YES + +== Columns of table article_tagbag + ARTICLE_ID | BIGINT | null | 64 | 0 | NO + COLOUR | CHARACTER VARYING | 255 | null | null | YES + NAME | CHARACTER VARYING | 255 | null | null | YES + +== Columns of table article_tagordered + TAGORDERED_ORDER | INTEGER | null | 32 | 0 | NO + ARTICLE_ID | BIGINT | null | 64 | 0 | NO + COLOUR | CHARACTER VARYING | 255 | null | null | YES + NAME | CHARACTER VARYING | 255 | null | null | YES + +== Columns of table article_strictset + ARTICLE_ID | BIGINT | null | 64 | 0 | NO + COLOUR | CHARACTER VARYING | 255 | null | null | NO + NAME | CHARACTER VARYING | 255 | null | null | NO + +primary key / unique constraints (table, columns): + ARTICLE_STRICTSET | PRIMARY KEY | ARTICLE_ID,COLOUR,NAME + ARTICLE_TAGORDERED | PRIMARY KEY | TAGORDERED_ORDER,ARTICLE_ID + +== Removing one of three elements +-- Set: remove Tag(jpa, blue) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select ts1_0.Article_id,ts1_0.name,ts1_0.colour from Article_tagSet ts1_0 where ts1_0.Article_id=? + sql> delete from Article_tagSet where Article_id=? + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + => true +-- Set with NOT NULL components: remove NnTag(jpa, blue) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select ss1_0.Article_id,ss1_0.name,ss1_0.colour from Article_strictSet ss1_0 where ss1_0.Article_id=? + sql> delete from Article_strictSet where Article_id=? and name=? and colour=? + => true +-- List (bag): remove Tag(jpa, blue) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select tb1_0.Article_id,tb1_0.name,tb1_0.colour from Article_tagBag tb1_0 where tb1_0.Article_id=? + sql> delete from Article_tagBag where Article_id=? + sql> insert into Article_tagBag (Article_id,name,colour) values (?,?,?) + sql> insert into Article_tagBag (Article_id,name,colour) values (?,?,?) + => true + inserts after the delete: 2 +-- List with @OrderColumn: remove Tag(jpa, blue) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select to1_0.Article_id,to1_0.tagOrdered_ORDER,to1_0.name,to1_0.colour from Article_tagOrdered to1_0 where to1_0.Article_id=? + sql> delete from Article_tagOrdered where Article_id=? and tagOrdered_ORDER=? + sql> update Article_tagOrdered set name=?,colour=? where Article_id=? and tagOrdered_ORDER=? + => true + +== Adding one element +-- Set: add Tag(hql, grey) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select ts1_0.Article_id,ts1_0.name,ts1_0.colour from Article_tagSet ts1_0 where ts1_0.Article_id=? + sql> delete from Article_tagSet where Article_id=? + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + => true +-- List (bag): add Tag(hql, grey) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select tb1_0.Article_id,tb1_0.name,tb1_0.colour from Article_tagBag tb1_0 where tb1_0.Article_id=? + sql> delete from Article_tagBag where Article_id=? + sql> insert into Article_tagBag (Article_id,name,colour) values (?,?,?) + sql> insert into Article_tagBag (Article_id,name,colour) values (?,?,?) + sql> insert into Article_tagBag (Article_id,name,colour) values (?,?,?) + => true +-- Set with NOT NULL components: add NnTag(hql, grey) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select ss1_0.Article_id,ss1_0.name,ss1_0.colour from Article_strictSet ss1_0 where ss1_0.Article_id=? + sql> insert into Article_strictSet (Article_id,name,colour) values (?,?,?) + => true +-- List with @OrderColumn: add Tag(hql, grey) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select to1_0.Article_id,to1_0.tagOrdered_ORDER,to1_0.name,to1_0.colour from Article_tagOrdered to1_0 where to1_0.Article_id=? + sql> insert into Article_tagOrdered (Article_id,tagOrdered_ORDER,name,colour) values (?,?,?,?) + => true + +== Replacing the whole collection with an equal one +-- Set: replace with new LinkedHashSet of equal records + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select ts1_0.Article_id,ts1_0.name,ts1_0.colour from Article_tagSet ts1_0 where ts1_0.Article_id=? + sql> delete from Article_tagSet where Article_id=? + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + => 3 diff --git a/embeddables/output/06-collection-nulls.txt b/embeddables/output/06-collection-nulls.txt new file mode 100644 index 0000000..841af38 --- /dev/null +++ b/embeddables/output/06-collection-nulls.txt @@ -0,0 +1,31 @@ +# Null components and null elements in a collection of records +# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25 +-- Set: add Tag(java, null) + sql> insert into Article (id) values (?) + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + => added + rows: [1 | null | java] +-- Set: add Tag(null, null) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select ts1_0.Article_id,ts1_0.name,ts1_0.colour from Article_tagSet ts1_0 where ts1_0.Article_id=? + sql> delete from Article_tagSet where Article_id=? + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + sql> insert into Article_tagSet (Article_id,name,colour) values (?,?,?) + => added + rows: [1 | null | null, 1 | null | java] +-- List (bag): add Tag(null, null) + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select tb1_0.Article_id,tb1_0.name,tb1_0.colour from Article_tagBag tb1_0 where tb1_0.Article_id=? + sql> insert into Article_tagBag (Article_id,name,colour) values (?,?,?) + => added + rows: [1 | null | null] +-- load tagBag + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select tb1_0.Article_id,tb1_0.name,tb1_0.colour from Article_tagBag tb1_0 where tb1_0.Article_id=? + => [] + (what a reader of the collection gets back) +-- List (bag): add a null element + sql> select a1_0.id from Article a1_0 where a1_0.id=? + sql> select tb1_0.Article_id,tb1_0.name,tb1_0.colour from Article_tagBag tb1_0 where tb1_0.Article_id=? + => added + rows: [1 | null | null] diff --git a/embeddables/output/07-equality.txt b/embeddables/output/07-equality.txt new file mode 100644 index 0000000..8e7e93e --- /dev/null +++ b/embeddables/output/07-equality.txt @@ -0,0 +1,32 @@ +# equals/hashCode of records, and comparing embeddables in HQL +# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25 +Money(10.0, INR).equals(Money(10.00, INR)) = false +Money(10.00, INR).equals(Money(10.00, INR)) = true +hashCodes of 10.0 vs 10.00 Money equal = false +new HashSet(List.of(10.0, 10.00)).size() = 2 + +== Comparing an embeddable in HQL +-- from Product p where p.price = :m (m = Money(10.0, INR)) + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where (p1_0.amount,p1_0.currency)=(?,?) + => [1] +-- from Product p where p.price in (:a, :b) + sql> select p1_0.id,p1_0.name,p1_0.amount,p1_0.currency from Product p1_0 where (p1_0.amount,p1_0.currency) in ((?,?),(?,?)) + => [1, 2] +-- select p.price from Product p order by p.id (an embeddable as a result) + sql> select p1_0.amount,p1_0.currency from Product p1_0 order by p1_0.id + => [Money[amount=10.00, currency=INR], Money[amount=20.00, currency=INR], null] +-- select p.price.amount from Product p order by p.price.amount desc + sql> select p1_0.amount from Product p1_0 order by p1_0.amount desc + => [20.00, 10.00, null] +-- select new Money(p.price.amount, 'USD') from Product p where p.id = 1 (constructor expression) + sql> select p1_0.amount,'USD' from Product p1_0 where p1_0.id=1 + => [Money[amount=10.00, currency=USD]] + +== A record as @EmbeddedId +Columns: [LINE | INTEGER | null | 32 | 0 | NO, ORDERID | BIGINT | null | 64 | 0 | NO, SKU | CHARACTER VARYING | 255 | null | null | YES] +-- find(OrderLine.class, new OrderLineId(7, 1)) + sql> select ol1_0.orderId,ol1_0.line,ol1_0.sku from OrderLine ol1_0 where (ol1_0.orderId,ol1_0.line) in ((?,?)) + => SKU-A +-- same session twice: find with two equal-but-distinct keys, same instance? + sql> select ol1_0.orderId,ol1_0.line,ol1_0.sku from OrderLine ol1_0 where (ol1_0.orderId,ol1_0.line) in ((?,?)) + => true diff --git a/embeddables/output/08-value-object.txt b/embeddables/output/08-value-object.txt new file mode 100644 index 0000000..b21db57 --- /dev/null +++ b/embeddables/output/08-value-object.txt @@ -0,0 +1,29 @@ +# record Email(String value) as a DDD value object +# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25 + +== Columns of table member + ID | BIGINT | null | 64 | 0 | NO + EMAIL | CHARACTER VARYING | 255 | null | null | YES +stored value: [1 | ankur@example.com] + +== Queries +-- from Member m where m.email = :e (e = new Email("ANKUR@example.com")) + sql> select m1_0.id,m1_0.email from Member m1_0 where m1_0.email=? + => 1 +-- from Member m where m.email.value like '%@example.com' + sql> select m1_0.id,m1_0.email from Member m1_0 where m1_0.email like '%@example.com' escape '' + => 1 +-- select m.email from Member m + sql> select m1_0.email from Member m1_0 + => [Email[value=ankur@example.com]] + +== Bad data already in the table +-- find Member 2 + sql> select m1_0.id,m1_0.email from Member m1_0 where m1_0.id=? + => InstantiationException: Could not instantiate entity 'com.ankurm.embeddables.Email' due to: null [root cause: IllegalArgumentException: not an email address: not-an-address] +-- from Member (loads both rows) + sql> select m1_0.id,m1_0.email from Member m1_0 order by m1_0.id + => InstantiationException: Could not instantiate entity 'com.ankurm.embeddables.Email' due to: null [root cause: IllegalArgumentException: not an email address: not-an-address] +-- select m.id from Member m (does not touch the Email) + sql> select m1_0.id from Member m1_0 order by m1_0.id + => [1, 2] diff --git a/embeddables/output/09-failures.txt b/embeddables/output/09-failures.txt new file mode 100644 index 0000000..fe964a1 --- /dev/null +++ b/embeddables/output/09-failures.txt @@ -0,0 +1,33 @@ +# Things that go wrong with record embeddables +# Hibernate ORM 7.4.17.Final, H2 2.4.240, JDK 25 + +== Same record embedded twice without @AttributeOverride + org.hibernate.MappingException: Column 'street' is duplicated in mapping for entity 'com.ankurm.embeddables.BadCustomer' (use '@Column(insertable=false, updatable=false)' when mapping multiple properties to the same column) + +== A component called value (record Handle(String value)) + session factory started; columns of table account: [] +-- persist Account(1, Handle(x)) + sql> insert into Account (value,id) values (?,?) + => SQLGrammarException: Could not prepare statement [Table "ACCOUNT" not found (this database is empty); SQL statement: [root cause: JdbcSQLSyntaxErrorException: Table "ACCOUNT" not found (this database is empty); SQL statement:] + +== The same DDL typed by hand into H2 (create table t(value varchar(5))) + Syntax error in SQL statement "create table t([*]value varchar(5))"; expected "identifier"; SQL statement: + +== A record that is not annotated @Embeddable, used with @Embedded (Holder.money is a PlainMoney) + session factory started; columns of table holder: [AMOUNT | NUMERIC | null | 38 | 2 | YES, ID | BIGINT | null | 64 | 0 | NO, CURRENCY | CHARACTER VARYING | 255 | null | null | YES] +-- persist Holder(1, PlainMoney(5, INR)) and load it + sql> insert into Holder (amount,currency,id) values (?,?,?) + sql> select h1_0.id,h1_0.amount,h1_0.currency from Holder h1_0 where h1_0.id=? + => PlainMoney[amount=5.00, currency=INR] + +== A record as @Entity + session factory started; columns of table recordentity: [ID | BIGINT | null | 64 | 0 | NO, NAME | CHARACTER VARYING | 255 | null | null | YES] +-- persist RecordEntity(1, first) + sql> insert into RecordEntity (name,id) values (?,?) + => persisted +-- find it back + sql> select re1_0.id,re1_0.name from RecordEntity re1_0 where re1_0.id=? + => InstantiationException: No default constructor for entity 'com.ankurm.embeddables.RecordEntity' +-- merge(new RecordEntity(1, second)) and find again + sql> select re1_0.id,re1_0.name from RecordEntity re1_0 where re1_0.id=? + => InstantiationException: No default constructor for entity 'com.ankurm.embeddables.RecordEntity' diff --git a/embeddables/output/10-setting-search.txt b/embeddables/output/10-setting-search.txt new file mode 100644 index 0000000..89d0814 --- /dev/null +++ b/embeddables/output/10-setting-search.txt @@ -0,0 +1,5 @@ +# hibernate-core-7.4.17.Final.jar: every class and resource searched for the text 'create_empty_composites' +$ grep -rl create_empty_composites | wc -l +0 +$ grep -rl 'hibernate.use_nationalized_character_data' | wc -l # control: a real setting is found +3 diff --git a/embeddables/pom.xml b/embeddables/pom.xml new file mode 100644 index 0000000..a6c5a37 --- /dev/null +++ b/embeddables/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + com.ankurm + embeddables + 1.0.0 + embeddables + Records and value objects in Hibernate 7: @Embeddable records, null handling, collections of embeddables, equality and DDD value objects (plain Hibernate on H2) + + + 25 + UTF-8 + + 7.4.17.Final + 3.2.0 + + + + + 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 + + ${hibernate.version} + + + + + + diff --git a/embeddables/scripts/run-all.sh b/embeddables/scripts/run-all.sh new file mode 100755 index 0000000..b2c938a --- /dev/null +++ b/embeddables/scripts/run-all.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Regenerates every file under output/. Needs JDK 25 and Maven 3.9; no database server, no Docker. +# ./scripts/run-all.sh +set -euo pipefail +cd "$(dirname "$0")/.." +mvn -B clean test +./scripts/search-setting.sh >/dev/null +ls -1 output diff --git a/embeddables/scripts/search-setting.sh b/embeddables/scripts/search-setting.sh new file mode 100755 index 0000000..f07d119 --- /dev/null +++ b/embeddables/scripts/search-setting.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Does the string "create_empty_composites" occur anywhere in the hibernate-core jar the build resolved? +# Writes output/10-setting-search.txt. Run after `mvn test` (or any build) so the jar is in ~/.m2. +set -euo pipefail +cd "$(dirname "$0")/.." +V=$(sed -n 's#.*\(.*\).*#\1#p' pom.xml | head -1) +JAR="$HOME/.m2/repository/org/hibernate/orm/hibernate-core/$V/hibernate-core-$V.jar" +TMP=$(mktemp -d) +unzip -q -o "$JAR" -d "$TMP" +mkdir -p output +{ + echo "# hibernate-core-$V.jar: every class and resource searched for the text 'create_empty_composites'" + echo "\$ grep -rl create_empty_composites | wc -l" + echo "$(grep -rl -a 'create_empty_composites' "$TMP" | wc -l)" + echo "\$ grep -rl 'hibernate.use_nationalized_character_data' | wc -l # control: a real setting is found" + echo "$(grep -rl -a 'hibernate.use_nationalized_character_data' "$TMP" | wc -l)" +} > output/10-setting-search.txt +rm -rf "$TMP" +cat output/10-setting-search.txt diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Account.java b/embeddables/src/main/java/com/ankurm/embeddables/Account.java new file mode 100644 index 0000000..0097aad --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Account.java @@ -0,0 +1,14 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Account { + + @Id + public Long id; + @Embedded + public Handle handle; +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Address.java b/embeddables/src/main/java/com/ankurm/embeddables/Address.java new file mode 100644 index 0000000..3039515 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Address.java @@ -0,0 +1,7 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embeddable; + +@Embeddable +public record Address(String street, String city, String zip, Geo geo) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Article.java b/embeddables/src/main/java/com/ankurm/embeddables/Article.java new file mode 100644 index 0000000..228c6e1 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Article.java @@ -0,0 +1,39 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.ElementCollection; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OrderColumn; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** The same record shape collected four ways: Set, plain List (a "bag"), List with @OrderColumn, Set with NOT NULL components. */ +@Entity +public class Article { + + @Id + public Long id; + + @ElementCollection + public Set tagSet = new LinkedHashSet<>(); + + @ElementCollection + public List tagBag = new ArrayList<>(); + + /** NOT NULL components: Hibernate can delete one element by its own columns. */ + @ElementCollection + public Set strictSet = new LinkedHashSet<>(); + + @ElementCollection + @OrderColumn + public List tagOrdered = new ArrayList<>(); + + protected Article() { + } + + public Article(Long id) { + this.id = id; + } +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/BadCustomer.java b/embeddables/src/main/java/com/ankurm/embeddables/BadCustomer.java new file mode 100644 index 0000000..8d9cfe2 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/BadCustomer.java @@ -0,0 +1,17 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +/** Two embedded Address attributes and no @AttributeOverride: the column names collide (T06). */ +@Entity +public class BadCustomer { + + @Id + public Long id; + @Embedded + public Address billing; + @Embedded + public Address shipping; +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Box.java b/embeddables/src/main/java/com/ankurm/embeddables/Box.java new file mode 100644 index 0000000..462e610 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Box.java @@ -0,0 +1,23 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Box { + + @Id + public Long id; + /** Optional Dim whose components are primitives. */ + @Embedded + public Dim dim; + + protected Box() { + } + + public Box(Long id, Dim dim) { + this.id = id; + this.dim = dim; + } +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Customer.java b/embeddables/src/main/java/com/ankurm/embeddables/Customer.java new file mode 100644 index 0000000..acec62c --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Customer.java @@ -0,0 +1,38 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.AttributeOverride; +import jakarta.persistence.AttributeOverrides; +import jakarta.persistence.Column; +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +/** The same record type twice: every column name must be overridden for the second use. */ +@Entity +public class Customer { + + @Id + public Long id; + + @Embedded + public Address billing; + + @Embedded + @AttributeOverrides({ + @AttributeOverride(name = "street", column = @Column(name = "ship_street")), + @AttributeOverride(name = "city", column = @Column(name = "ship_city")), + @AttributeOverride(name = "zip", column = @Column(name = "ship_zip")), + @AttributeOverride(name = "geo.lat", column = @Column(name = "ship_lat")), + @AttributeOverride(name = "geo.lon", column = @Column(name = "ship_lon")) + }) + public Address shipping; + + protected Customer() { + } + + public Customer(Long id, Address billing, Address shipping) { + this.id = id; + this.billing = billing; + this.shipping = shipping; + } +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Dim.java b/embeddables/src/main/java/com/ankurm/embeddables/Dim.java new file mode 100644 index 0000000..b8cafaf --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Dim.java @@ -0,0 +1,8 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embeddable; + +/** Primitive components: they can never be null in Java, and Hibernate maps them NOT NULL. */ +@Embeddable +public record Dim(int width, int height) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Email.java b/embeddables/src/main/java/com/ankurm/embeddables/Email.java new file mode 100644 index 0000000..461c7a6 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Email.java @@ -0,0 +1,21 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import java.util.Locale; + +/** A DDD value object (column renamed: a column called "value" is a reserved word in H2, see Handle and T06): one component, validated and normalised in the constructor, equal by value. */ +@Embeddable +public record Email(@Column(name = "email") String value) { + + public Email { + if (value == null || !value.contains("@")) { + throw new IllegalArgumentException("not an email address: " + value); + } + value = value.toLowerCase(Locale.ROOT); + } + + public String domain() { + return value.substring(value.indexOf('@') + 1); + } +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Geo.java b/embeddables/src/main/java/com/ankurm/embeddables/Geo.java new file mode 100644 index 0000000..b1c3566 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Geo.java @@ -0,0 +1,8 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embeddable; + +/** An embeddable nested inside another embeddable (Address). Primitive components cannot be null. */ +@Embeddable +public record Geo(Double lat, Double lon) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Handle.java b/embeddables/src/main/java/com/ankurm/embeddables/Handle.java new file mode 100644 index 0000000..88e53e4 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Handle.java @@ -0,0 +1,8 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embeddable; + +/** One component called "value": the natural name, and a reserved word in H2 (T06). */ +@Embeddable +public record Handle(String value) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Holder.java b/embeddables/src/main/java/com/ankurm/embeddables/Holder.java new file mode 100644 index 0000000..cb16394 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Holder.java @@ -0,0 +1,15 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +/** Embeds a record that is not annotated @Embeddable. Only T06 loads this class. */ +@Entity +public class Holder { + + @Id + public Long id; + @Embedded + public PlainMoney money; +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Member.java b/embeddables/src/main/java/com/ankurm/embeddables/Member.java new file mode 100644 index 0000000..5fc8232 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Member.java @@ -0,0 +1,22 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Member { + + @Id + public Long id; + @Embedded + public Email email; + + protected Member() { + } + + public Member(Long id, Email email) { + this.id = id; + this.email = email; + } +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Money.java b/embeddables/src/main/java/com/ankurm/embeddables/Money.java new file mode 100644 index 0000000..5496af9 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Money.java @@ -0,0 +1,12 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import java.math.BigDecimal; + +/** The simplest embeddable record: two components, two columns, no no-arg constructor, no setters. */ +@Embeddable +public record Money( + @Column(precision = 12, scale = 2) BigDecimal amount, + @Column(length = 3) String currency) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/NnTag.java b/embeddables/src/main/java/com/ankurm/embeddables/NnTag.java new file mode 100644 index 0000000..1ac23ab --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/NnTag.java @@ -0,0 +1,11 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; + +/** Same shape as Tag, but both columns NOT NULL. That changes how Hibernate deletes elements. */ +@Embeddable +public record NnTag( + @Column(nullable = false) String name, + @Column(nullable = false) String colour) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/OrderLine.java b/embeddables/src/main/java/com/ankurm/embeddables/OrderLine.java new file mode 100644 index 0000000..91b69b8 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/OrderLine.java @@ -0,0 +1,20 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; + +@Entity +public class OrderLine { + + @EmbeddedId + public OrderLineId id; + public String sku; + + protected OrderLine() { + } + + public OrderLine(OrderLineId id, String sku) { + this.id = id; + this.sku = sku; + } +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/OrderLineId.java b/embeddables/src/main/java/com/ankurm/embeddables/OrderLineId.java new file mode 100644 index 0000000..1c4ca42 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/OrderLineId.java @@ -0,0 +1,8 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embeddable; + +/** A composite key as a record: equals/hashCode come for free, which is exactly what a key needs. */ +@Embeddable +public record OrderLineId(Long orderId, Integer line) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Parcel.java b/embeddables/src/main/java/com/ankurm/embeddables/Parcel.java new file mode 100644 index 0000000..5045e17 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Parcel.java @@ -0,0 +1,22 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Parcel { + + @Id + public Long id; + @Embedded + public Weight weight; + + protected Parcel() { + } + + public Parcel(Long id, Weight weight) { + this.id = id; + this.weight = weight; + } +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/PlainMoney.java b/embeddables/src/main/java/com/ankurm/embeddables/PlainMoney.java new file mode 100644 index 0000000..28a7b98 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/PlainMoney.java @@ -0,0 +1,5 @@ +package com.ankurm.embeddables; + +/** A record that forgot @Embeddable. Used by T06 to show the failure. */ +public record PlainMoney(java.math.BigDecimal amount, String currency) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Product.java b/embeddables/src/main/java/com/ankurm/embeddables/Product.java new file mode 100644 index 0000000..a7283c8 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Product.java @@ -0,0 +1,25 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embedded; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Product { + + @Id + public Long id; + public String name; + /** Nullable on purpose: what is a Product with "no price" in the database? */ + @Embedded + public Money price; + + protected Product() { + } + + public Product(Long id, String name, Money price) { + this.id = id; + this.name = name; + this.price = price; + } +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/RecordEntity.java b/embeddables/src/main/java/com/ankurm/embeddables/RecordEntity.java new file mode 100644 index 0000000..8be17c3 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/RecordEntity.java @@ -0,0 +1,9 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +/** A record annotated @Entity. Compiles; Hibernate refuses it at startup (T06). */ +@Entity +public record RecordEntity(@Id Long id, String name) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Tag.java b/embeddables/src/main/java/com/ankurm/embeddables/Tag.java new file mode 100644 index 0000000..0ed3fd7 --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Tag.java @@ -0,0 +1,7 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embeddable; + +@Embeddable +public record Tag(String name, String colour) { +} diff --git a/embeddables/src/main/java/com/ankurm/embeddables/Weight.java b/embeddables/src/main/java/com/ankurm/embeddables/Weight.java new file mode 100644 index 0000000..d5d896a --- /dev/null +++ b/embeddables/src/main/java/com/ankurm/embeddables/Weight.java @@ -0,0 +1,15 @@ +package com.ankurm.embeddables; + +import jakarta.persistence.Embeddable; +import java.math.BigDecimal; +import java.util.Objects; + +/** A record that refuses nulls in its compact constructor: the all-or-nothing value object. */ +@Embeddable +public record Weight(BigDecimal magnitude, String unit) { + + public Weight { + Objects.requireNonNull(magnitude, "magnitude"); + Objects.requireNonNull(unit, "unit"); + } +} diff --git a/embeddables/src/test/java/com/ankurm/embeddables/Db.java b/embeddables/src/test/java/com/ankurm/embeddables/Db.java new file mode 100644 index 0000000..855e69d --- /dev/null +++ b/embeddables/src/test/java/com/ankurm/embeddables/Db.java @@ -0,0 +1,140 @@ +package com.ankurm.embeddables; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +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.StandardServiceRegistryBuilder; +import org.hibernate.resource.jdbc.spi.StatementInspector; + +/** In-memory H2, one SessionFactory, every prepared SQL statement captured so tests can show and assert it. */ +final class Db implements AutoCloseable { + + final List sql = new CopyOnWriteArrayList<>(); + final SessionFactory sf; + List last = List.of(); + + Db(Class... entities) { + this(Map.of(), entities); + } + + Db(Map extra, Class... entities) { + StatementInspector inspector = s -> { + sql.add(s); + return s; + }; + StandardServiceRegistryBuilder b = new StandardServiceRegistryBuilder() + .applySetting("hibernate.connection.url", "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1") + .applySetting("hibernate.connection.username", "sa") + .applySetting("hibernate.connection.password", "") + .applySetting("hibernate.hbm2ddl.auto", "create-drop") + .applySetting("hibernate.session_factory.statement_inspector", inspector); + extra.forEach(b::applySetting); + MetadataSources src = new MetadataSources(b.build()); + for (Class c : entities) { + src.addAnnotatedClass(c); + } + this.sf = src.buildMetadata().buildSessionFactory(); + } + + /** Runs native SQL in its own session; the captured SQL list is cleared afterwards. */ + void exec(String... statements) { + try (Session s = sf.openSession()) { + s.doWork(c -> { + for (String st : statements) { + try (var ps = c.createStatement()) { + ps.execute(st); + } + catch (java.sql.SQLException e) { + throw new IllegalStateException(st, e); + } + } + }); + } + sql.clear(); + } + + /** Native query rows, each row joined with " | ". */ + List rows(String query) { + List out = new ArrayList<>(); + try (Session s = sf.openSession()) { + s.doWork(c -> { + try (var st = c.createStatement(); var rs = st.executeQuery(query)) { + int n = rs.getMetaData().getColumnCount(); + while (rs.next()) { + List cells = new ArrayList<>(); + for (int i = 1; i <= n; i++) { + cells.add(String.valueOf(rs.getObject(i))); + } + out.add(String.join(" | ", cells)); + } + } + catch (java.sql.SQLException e) { + throw new IllegalStateException(query, e); + } + }); + } + sql.clear(); + return out; + } + + /** Column name, type and nullability of a table, as the database sees it. */ + List columns(String table) { + return rows("select column_name, data_type, character_maximum_length, numeric_precision, numeric_scale, is_nullable " + + "from information_schema.columns where table_name = '" + table.toUpperCase() + "' order by ordinal_position"); + } + + /** One transcript step: label, the SQL Hibernate prepared, and what the code returned (or the exception it threw). */ + String step(Transcript t, String label, Function work) { + sql.clear(); + String result; + try (Session s = sf.openSession()) { + var tx = s.beginTransaction(); + try { + result = String.valueOf(work.apply(s)); + tx.commit(); + } + catch (RuntimeException ex) { + tx.rollback(); + Throwable root = ex; + while (root.getCause() != null && root.getCause() != root) { + root = root.getCause(); + } + result = ex.getClass().getSimpleName() + ": " + String.valueOf(ex.getMessage()).lines().findFirst().orElse("") + + (root != ex ? " [root cause: " + root.getClass().getSimpleName() + ": " + + String.valueOf(root.getMessage()).lines().findFirst().orElse("") + "]" : ""); + } + } + last = List.copyOf(sql); + t.step(label, last); + t.line(" => " + result); + return result; + } + + void run(Consumer work) { + inTx(s -> { + work.accept(s); + return null; + }); + } + + R inTx(Function work) { + try (Session s = sf.openSession()) { + var tx = s.beginTransaction(); + R r = work.apply(s); + tx.commit(); + return r; + } + } + + @Override + public void close() { + sf.close(); + } +} diff --git a/embeddables/src/test/java/com/ankurm/embeddables/T01_BasicTest.java b/embeddables/src/test/java/com/ankurm/embeddables/T01_BasicTest.java new file mode 100644 index 0000000..025af46 --- /dev/null +++ b/embeddables/src/test/java/com/ankurm/embeddables/T01_BasicTest.java @@ -0,0 +1,77 @@ +package com.ankurm.embeddables; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; + +/** What a record embeddable maps to, how it round-trips, and how an update looks (records cannot be mutated). */ +class T01_BasicTest { + + @Test + void basic() { + Transcript t = new Transcript("01-basic", "@Embeddable record Money(amount, currency) inside Product"); + try (Db db = new Db(Product.class)) { + t.heading("Columns of table product"); + var cols = db.columns("product"); + t.lines(cols, " "); + assertThat(cols).anyMatch(c -> c.startsWith("AMOUNT")); + + t.heading("Insert and load"); + db.step(t, "persist Product(1, Keyboard, Money(10.5, INR))", s -> { + s.persist(new Product(1L, "Keyboard", new Money(new BigDecimal("10.5"), "INR"))); + return "persisted"; + }); + assertThat(db.last).anyMatch(x -> x.startsWith("insert into Product")); + t.line(" in database: " + db.rows("select * from product")); + String loaded = db.step(t, "load Product 1 in a new session", s -> s.find(Product.class, 1L).price); + assertThat(loaded).isEqualTo("Money[amount=10.50, currency=INR]"); + Money before = new Money(new BigDecimal("10.5"), "INR"); + Money after = db.inTx(s -> s.find(Product.class, 1L).price); + t.line(" in-memory Money(10.5, INR).equals(Money loaded back from NUMERIC(12,2)) = " + before.equals(after)); + assertThat(before).isNotEqualTo(after); + + t.heading("Updating: replace the whole record"); + db.step(t, "replace price with Money(12.00, INR)", s -> { + s.find(Product.class, 1L).price = new Money(new BigDecimal("12.00"), "INR"); + return "replaced"; + }); + assertThat(db.last).anyMatch(x -> x.startsWith("update Product set")); + db.step(t, "replace price with an equal-valued Money(12.0, INR) (scale 1 vs 2)", s -> { + s.find(Product.class, 1L).price = new Money(new BigDecimal("12.0"), "INR"); + return "replaced"; + }); + t.line(" record equals says: " + new Money(new BigDecimal("12.0"), "INR").equals(new Money(new BigDecimal("12.00"), "INR"))); + t.line(" update issued: " + db.last.stream().anyMatch(x -> x.startsWith("update"))); + db.step(t, "replace price with a really different Money(13.00, INR)", s -> { + s.find(Product.class, 1L).price = new Money(new BigDecimal("13.00"), "INR"); + return "replaced"; + }); + db.step(t, "replace price with an identical new instance Money(13.00, INR)", s -> { + s.find(Product.class, 1L).price = new Money(new BigDecimal("13.00"), "INR"); + return "replaced"; + }); + assertThat(db.last).noneMatch(x -> x.startsWith("update")); + } + t.write(); + } + + @Test + void sameRecordTwice() { + Transcript t = new Transcript("02-two-uses", "The same record type embedded twice (Address as billing and shipping), with a nested record (Geo)"); + try (Db db = new Db(Customer.class)) { + t.heading("Columns of table customer"); + var cols = db.columns("customer"); + t.lines(cols, " "); + assertThat(cols).hasSize(11); + db.run(s -> s.persist(new Customer(1L, new Address("1 MG Road", "Pune", "411001", new Geo(18.5, 73.8)), + new Address("9 Marine Dr", "Mumbai", "400020", null)))); + t.heading("Load it back"); + db.step(t, "find Customer 1", s -> { + Customer c = s.find(Customer.class, 1L); + return "billing=" + c.billing + " shipping=" + c.shipping; + }); + } + t.write(); + } +} diff --git a/embeddables/src/test/java/com/ankurm/embeddables/T02_NullTest.java b/embeddables/src/test/java/com/ankurm/embeddables/T02_NullTest.java new file mode 100644 index 0000000..4043826 --- /dev/null +++ b/embeddables/src/test/java/com/ankurm/embeddables/T02_NullTest.java @@ -0,0 +1,88 @@ +package com.ankurm.embeddables; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** What happens to a record embeddable when its columns are null, entirely or partly. */ +class T02_NullTest { + + @Test + void nulls() { + Transcript t = new Transcript("03-nulls", "Null handling for record embeddables"); + try (Db db = new Db(Product.class, Customer.class)) { + t.heading("A null embedded attribute is written as all-null columns"); + db.step(t, "persist Product(1, Mouse, price = null)", s -> { + s.persist(new Product(1L, "Mouse", null)); + return "persisted"; + }); + t.line(" in database: " + db.rows("select id, name, amount, currency from product")); + String r = db.step(t, "load it back", s -> s.find(Product.class, 1L).price); + assertThat(r).isEqualTo("null"); + + t.heading("Partly null columns give a record with null components"); + db.run(s -> s.persist(new Product(2L, "Cable", new Money(null, "INR")))); + String r2 = db.step(t, "persist Money(null, INR), load it back", s -> s.find(Product.class, 2L).price); + assertThat(r2).isEqualTo("Money[amount=null, currency=INR]"); + + t.heading("Querying for 'no price'"); + db.step(t, "from Product p where p.price is null", s -> s.createSelectionQuery("from Product p where p.price is null", Product.class).getResultList().stream().map(p -> p.id).toList()); + db.step(t, "from Product p where p.price.amount is null", s -> s.createSelectionQuery("from Product p where p.price.amount is null", Product.class).getResultList().stream().map(p -> p.id).toList()); + + t.heading("Nested embeddable: Address with all-null Geo inside a non-null Address"); + db.run(s -> s.persist(new Customer(1L, new Address("1 MG Road", "Pune", "411001", null), null))); + db.step(t, "load Customer 1 (geo columns all null, shipping columns all null)", s -> { + Customer c = s.find(Customer.class, 1L); + return "billing=" + c.billing + " shipping=" + c.shipping; + }); + Boolean geoIsNull = db.inTx(s -> s.find(Customer.class, 1L).billing.geo() == null); + assertThat(geoIsNull).isTrue(); + } + + t.heading("A compact constructor that rejects nulls (Weight)"); + try (Db db = new Db(Parcel.class)) { + db.step(t, "persist Parcel(1, null) and load it", s -> { + s.persist(new Parcel(1L, null)); + s.flush(); + s.clear(); + return s.find(Parcel.class, 1L).weight; + }); + assertThat(db.rows("select count(*) from parcel where magnitude is null")).containsExactly("1"); + db.exec("insert into parcel (id, magnitude, unit) values (2, null, 'kg')"); + String r = db.step(t, "row with value null, unit 'kg': find Parcel 2", s -> s.find(Parcel.class, 2L).weight); + assertThat(r).contains("NullPointerException"); + } + + t.heading("hibernate.create_empty_composites.enabled=true (a setting often cited online for this; see output/10-setting-search.txt)"); + try (Db db = new Db(Map.of("hibernate.create_empty_composites.enabled", "true"), Product.class, Parcel.class)) { + db.run(s -> s.persist(new Product(1L, "Mouse", null))); + String r = db.step(t, "Product with all-null price columns, load it (Money has no validation)", s -> s.find(Product.class, 1L).price); + t.line(" (same as the default above: the setting changed nothing)"); + db.run(s -> s.persist(new Parcel(1L, null))); + db.step(t, "Parcel with all-null weight columns, load it (Weight rejects nulls)", s -> s.find(Parcel.class, 1L).weight); + } + t.write(); + } + + @Test + void primitivesAndNotNull() { + Transcript t = new Transcript("04-primitives", "A record with primitive components (Dim(int width, int height)) as an optional embedded attribute"); + try (Db db = new Db(Box.class)) { + t.heading("Columns of table box"); + var cols = db.columns("box"); + t.lines(cols, " "); + db.step(t, "persist Box(1, Dim(3, 4))", s -> { + s.persist(new Box(1L, new Dim(3, 4))); + return "persisted"; + }); + String r = db.step(t, "persist Box(2, null)", s -> { + s.persist(new Box(2L, null)); + return "persisted"; + }); + t.line(" rows: " + db.rows("select * from box order by id")); + assertThat(db.rows("select count(*) from box where width is null and height is null")).containsExactly("1"); + } + t.write(); + } +} diff --git a/embeddables/src/test/java/com/ankurm/embeddables/T03_CollectionTest.java b/embeddables/src/test/java/com/ankurm/embeddables/T03_CollectionTest.java new file mode 100644 index 0000000..1bbb1fb --- /dev/null +++ b/embeddables/src/test/java/com/ankurm/embeddables/T03_CollectionTest.java @@ -0,0 +1,89 @@ +package com.ankurm.embeddables; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +/** @ElementCollection of a record: the table, the SQL for add and remove, and what a record's equals has to do with it. */ +class T03_CollectionTest { + + @Test + void collections() { + Transcript t = new Transcript("05-collections", "@ElementCollection of record Tag(name, colour): Set vs List (bag) vs List with @OrderColumn"); + try (Db db = new Db(Article.class)) { + for (String tbl : new String[] { "article_tagset", "article_tagbag", "article_tagordered", "article_strictset" }) { + t.heading("Columns of table " + tbl); + t.lines(db.columns(tbl), " "); + } + t.line(""); + t.line("primary key / unique constraints (table, columns):"); + t.lines(db.rows("select tc.table_name, tc.constraint_type, listagg(k.column_name, ',') within group (order by k.ordinal_position) " + + "from information_schema.table_constraints tc join information_schema.key_column_usage k on k.constraint_name = tc.constraint_name " + + "where tc.table_name like 'ARTICLE_%' and tc.constraint_type = 'PRIMARY KEY' group by tc.table_name, tc.constraint_type order by 1"), " "); + + db.run(s -> { + Article a = new Article(1L); + for (var l : java.util.List.>of(a.tagSet, a.tagBag, a.tagOrdered)) { + l.addAll(java.util.List.of(new Tag("java", "red"), new Tag("jpa", "blue"), new Tag("sql", "green"))); + } + a.strictSet.addAll(java.util.List.of(new NnTag("java", "red"), new NnTag("jpa", "blue"), new NnTag("sql", "green"))); + s.persist(a); + }); + t.heading("Removing one of three elements"); + db.step(t, "Set: remove Tag(jpa, blue)", s -> s.find(Article.class, 1L).tagSet.remove(new Tag("jpa", "blue"))); + assertThat(db.last).filteredOn(x -> x.startsWith("insert")).hasSize(2); + db.step(t, "Set with NOT NULL components: remove NnTag(jpa, blue)", s -> s.find(Article.class, 1L).strictSet.remove(new NnTag("jpa", "blue"))); + assertThat(db.last).filteredOn(x -> x.startsWith("insert")).isEmpty(); + db.step(t, "List (bag): remove Tag(jpa, blue)", s -> s.find(Article.class, 1L).tagBag.remove(new Tag("jpa", "blue"))); + long bagInserts = db.last.stream().filter(x -> x.startsWith("insert")).count(); + t.line(" inserts after the delete: " + bagInserts); + assertThat(bagInserts).isEqualTo(2); + db.step(t, "List with @OrderColumn: remove Tag(jpa, blue)", s -> s.find(Article.class, 1L).tagOrdered.remove(new Tag("jpa", "blue"))); + t.heading("Adding one element"); + db.step(t, "Set: add Tag(hql, grey)", s -> s.find(Article.class, 1L).tagSet.add(new Tag("hql", "grey"))); + db.step(t, "List (bag): add Tag(hql, grey)", s -> s.find(Article.class, 1L).tagBag.add(new Tag("hql", "grey"))); + db.step(t, "Set with NOT NULL components: add NnTag(hql, grey)", s -> s.find(Article.class, 1L).strictSet.add(new NnTag("hql", "grey"))); + db.step(t, "List with @OrderColumn: add Tag(hql, grey)", s -> s.find(Article.class, 1L).tagOrdered.add(new Tag("hql", "grey"))); + t.heading("Replacing the whole collection with an equal one"); + db.step(t, "Set: replace with new LinkedHashSet of equal records", s -> { + Article a = s.find(Article.class, 1L); + a.tagSet = new java.util.LinkedHashSet<>(a.tagSet); + return a.tagSet.size(); + }); + } + t.write(); + } + + @Test + void nullsInsideElements() { + Transcript t = new Transcript("06-collection-nulls", "Null components and null elements in a collection of records"); + try (Db db = new Db(Article.class)) { + db.step(t, "Set: add Tag(java, null)", s -> { + s.persist(new Article(1L)); + s.find(Article.class, 1L).tagSet.add(new Tag("java", null)); + return "added"; + }); + t.line(" rows: " + db.rows("select * from article_tagset")); + db.step(t, "Set: add Tag(null, null)", s -> { + s.find(Article.class, 1L).tagSet.add(new Tag(null, null)); + return "added"; + }); + t.line(" rows: " + db.rows("select * from article_tagset")); + db.step(t, "List (bag): add Tag(null, null)", s -> { + s.find(Article.class, 1L).tagBag.add(new Tag(null, null)); + return "added"; + }); + t.line(" rows: " + db.rows("select * from article_tagbag")); + String r = db.step(t, "load tagBag", s -> s.find(Article.class, 1L).tagBag); + t.line(" (what a reader of the collection gets back)"); + String r2 = db.step(t, "List (bag): add a null element", s -> { + s.find(Article.class, 1L).tagBag.add(null); + return "added"; + }); + t.line(" rows: " + db.rows("select * from article_tagbag")); + assertThat(r).isNotNull(); + assertThat(r2).isNotNull(); + } + t.write(); + } +} diff --git a/embeddables/src/test/java/com/ankurm/embeddables/T04_EqualityTest.java b/embeddables/src/test/java/com/ankurm/embeddables/T04_EqualityTest.java new file mode 100644 index 0000000..88f2f47 --- /dev/null +++ b/embeddables/src/test/java/com/ankurm/embeddables/T04_EqualityTest.java @@ -0,0 +1,56 @@ +package com.ankurm.embeddables; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; + +/** Record equality versus database equality, embeddables in HQL, and a record as @EmbeddedId. */ +class T04_EqualityTest { + + @Test + void equality() { + Transcript t = new Transcript("07-equality", "equals/hashCode of records, and comparing embeddables in HQL"); + Money a = new Money(new BigDecimal("10.0"), "INR"); + Money b = new Money(new BigDecimal("10.00"), "INR"); + Money c = new Money(new BigDecimal("10.00"), "INR"); + t.line("Money(10.0, INR).equals(Money(10.00, INR)) = " + a.equals(b)); + t.line("Money(10.00, INR).equals(Money(10.00, INR)) = " + b.equals(c)); + t.line("hashCodes of 10.0 vs 10.00 Money equal = " + (a.hashCode() == b.hashCode())); + t.line("new HashSet(List.of(10.0, 10.00)).size() = " + new java.util.HashSet<>(java.util.List.of(a, b)).size()); + assertThat(a).isNotEqualTo(b); + assertThat(b).isEqualTo(c); + + try (Db db = new Db(Product.class, Member.class, OrderLine.class)) { + db.run(s -> { + s.persist(new Product(1L, "Keyboard", new Money(new BigDecimal("10.00"), "INR"))); + s.persist(new Product(2L, "Mouse", new Money(new BigDecimal("20.00"), "INR"))); + s.persist(new Product(3L, "Cable", null)); + }); + t.heading("Comparing an embeddable in HQL"); + db.step(t, "from Product p where p.price = :m (m = Money(10.0, INR))", s -> s.createSelectionQuery("from Product p where p.price = :m", Product.class) + .setParameter("m", a).getResultList().stream().map(p -> p.id).toList()); + assertThat(db.last).anyMatch(x -> x.contains("(p1_0.amount,p1_0.currency)=(?,?)")); + db.step(t, "from Product p where p.price in (:a, :b)", s -> s.createSelectionQuery("from Product p where p.price in (:a, :b)", Product.class) + .setParameter("a", a).setParameter("b", new Money(new BigDecimal("20"), "INR")).getResultList().stream().map(p -> p.id).toList()); + db.step(t, "select p.price from Product p order by p.id (an embeddable as a result)", s -> s.createSelectionQuery("select p.price from Product p order by p.id", Money.class) + .getResultList()); + db.step(t, "select p.price.amount from Product p order by p.price.amount desc", s -> s.createSelectionQuery("select p.price.amount from Product p order by p.price.amount desc", BigDecimal.class) + .getResultList()); + db.step(t, "select new Money(p.price.amount, 'USD') from Product p where p.id = 1 (constructor expression)", s -> + s.createSelectionQuery("select new com.ankurm.embeddables.Money(p.price.amount, 'USD') from Product p where p.id = 1", Money.class).getResultList()); + + t.heading("A record as @EmbeddedId"); + db.run(s -> s.persist(new OrderLine(new OrderLineId(7L, 1), "SKU-A"))); + t.line("Columns: " + db.columns("orderline")); + String r = db.step(t, "find(OrderLine.class, new OrderLineId(7, 1))", s -> s.find(OrderLine.class, new OrderLineId(7L, 1)).sku); + assertThat(r).isEqualTo("SKU-A"); + db.step(t, "same session twice: find with two equal-but-distinct keys, same instance?", s -> { + OrderLine x = s.find(OrderLine.class, new OrderLineId(7L, 1)); + OrderLine y = s.find(OrderLine.class, new OrderLineId(7L, 1)); + return x == y; + }); + } + t.write(); + } +} diff --git a/embeddables/src/test/java/com/ankurm/embeddables/T05_ValueObjectTest.java b/embeddables/src/test/java/com/ankurm/embeddables/T05_ValueObjectTest.java new file mode 100644 index 0000000..c611226 --- /dev/null +++ b/embeddables/src/test/java/com/ankurm/embeddables/T05_ValueObjectTest.java @@ -0,0 +1,37 @@ +package com.ankurm.embeddables; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +/** A one-component value object (Email): column naming, querying, normalisation and bad data in the database. */ +class T05_ValueObjectTest { + + @Test + void email() { + Transcript t = new Transcript("08-value-object", "record Email(String value) as a DDD value object"); + try (Db db = new Db(Member.class)) { + t.heading("Columns of table member"); + t.lines(db.columns("member"), " "); + db.run(s -> s.persist(new Member(1L, new Email("Ankur@Example.COM")))); + t.line("stored value: " + db.rows("select * from member")); + assertThat(db.rows("select * from member").get(0)).contains("ankur@example.com"); + + t.heading("Queries"); + db.step(t, "from Member m where m.email = :e (e = new Email(\"ANKUR@example.com\"))", s -> s.createSelectionQuery("from Member m where m.email = :e", Member.class) + .setParameter("e", new Email("ANKUR@example.com")).getResultList().size()); + db.step(t, "from Member m where m.email.value like '%@example.com'", s -> s.createSelectionQuery("from Member m where m.email.value like '%@example.com'", Member.class) + .getResultList().size()); + db.step(t, "select m.email from Member m", s -> s.createSelectionQuery("select m.email from Member m", Email.class).getResultList()); + + t.heading("Bad data already in the table"); + db.exec("insert into member (id, email) values (2, 'not-an-address')"); + String r = db.step(t, "find Member 2", s -> s.find(Member.class, 2L)); + assertThat(r).contains("not an email address"); + String r2 = db.step(t, "from Member (loads both rows)", s -> s.createSelectionQuery("from Member order by id", Member.class).getResultList().size()); + assertThat(r2).contains("not an email address"); + db.step(t, "select m.id from Member m (does not touch the Email)", s -> s.createSelectionQuery("select m.id from Member m order by m.id", Long.class).getResultList()); + } + t.write(); + } +} diff --git a/embeddables/src/test/java/com/ankurm/embeddables/T06_FailuresTest.java b/embeddables/src/test/java/com/ankurm/embeddables/T06_FailuresTest.java new file mode 100644 index 0000000..0ed6246 --- /dev/null +++ b/embeddables/src/test/java/com/ankurm/embeddables/T06_FailuresTest.java @@ -0,0 +1,80 @@ +package com.ankurm.embeddables; + +import org.junit.jupiter.api.Test; + +/** What goes wrong at startup or first use: column collisions, a reserved-word column, and records where they should not be. */ +class T06_FailuresTest { + + @Test + void failures() { + Transcript t = new Transcript("09-failures", "Things that go wrong with record embeddables"); + + t.heading("Same record embedded twice without @AttributeOverride"); + try (Db db = new Db(BadCustomer.class)) { + t.line(" NO ERROR, session factory started"); + } + catch (RuntimeException ex) { + t.line(" " + ex.getClass().getName() + ": " + String.valueOf(ex.getMessage()).lines().findFirst().orElse("")); + } + + t.heading("A component called value (record Handle(String value))"); + try (Db db = new Db(Account.class)) { + t.line(" session factory started; columns of table account: " + db.columns("account")); + db.step(t, "persist Account(1, Handle(x))", s -> { + Account a = new Account(); + a.id = 1L; + a.handle = new Handle("x"); + s.persist(a); + return "persisted"; + }); + } + + t.heading("The same DDL typed by hand into H2 (create table t(value varchar(5)))"); + try (Db db = new Db(Product.class)) { + try { + db.exec("create table t(value varchar(5))"); + t.line(" NO ERROR"); + } + catch (IllegalStateException ex) { + t.line(" " + String.valueOf(ex.getCause().getMessage()).lines().findFirst().orElse("")); + } + } + + t.heading("A record that is not annotated @Embeddable, used with @Embedded (Holder.money is a PlainMoney)"); + try (Db db = new Db(Holder.class)) { + t.line(" session factory started; columns of table holder: " + db.columns("holder")); + db.step(t, "persist Holder(1, PlainMoney(5, INR)) and load it", s -> { + Holder h = new Holder(); + h.id = 1L; + h.money = new PlainMoney(new java.math.BigDecimal("5"), "INR"); + s.persist(h); + s.flush(); + s.clear(); + return s.find(Holder.class, 1L).money; + }); + } + catch (RuntimeException ex) { + t.line(" " + ex.getClass().getName() + ": " + String.valueOf(ex.getMessage()).lines().findFirst().orElse("")); + } + + t.heading("A record as @Entity"); + try (Db db = new Db(RecordEntity.class)) { + t.line(" session factory started; columns of table recordentity: " + db.columns("recordentity")); + db.step(t, "persist RecordEntity(1, first)", s -> { + s.persist(new RecordEntity(1L, "first")); + return "persisted"; + }); + db.step(t, "find it back", s -> s.find(RecordEntity.class, 1L)); + db.step(t, "merge(new RecordEntity(1, second)) and find again", s -> { + s.merge(new RecordEntity(1L, "second")); + s.flush(); + s.clear(); + return s.find(RecordEntity.class, 1L); + }); + } + catch (RuntimeException ex) { + t.line(" " + ex.getClass().getName() + ": " + String.valueOf(ex.getMessage()).lines().findFirst().orElse("")); + } + t.write(); + } +} diff --git a/embeddables/src/test/java/com/ankurm/embeddables/Transcript.java b/embeddables/src/test/java/com/ankurm/embeddables/Transcript.java new file mode 100644 index 0000000..b18c767 --- /dev/null +++ b/embeddables/src/test/java/com/ankurm/embeddables/Transcript.java @@ -0,0 +1,61 @@ +package com.ankurm.embeddables; + +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.txt; the tests assert the same facts. */ +final class Transcript { + + static final String VERSION = System.getProperty("h.version", "?"); + + private final List lines = new ArrayList<>(); + private final Path file; + + Transcript(String name, String title) { + this.file = Path.of("output", name + ".txt"); + line("# " + title); + line("# Hibernate ORM " + VERSION + ", H2 2.4.240, JDK " + Runtime.version().feature()); + } + + Transcript line(String s) { + lines.add(s); + return this; + } + + Transcript heading(String s) { + line(""); + return line("== " + s); + } + + Transcript lines(List ls, String prefix) { + for (String s : ls) { + line(prefix + s); + } + return this; + } + + /** A step: the label, then every SQL statement Hibernate prepared during it. */ + Transcript step(String label, List 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); + } + } +}