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 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b3obqqePfZ9m2Jk5Ub
This commit is contained in:
@@ -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`) |
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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]
|
||||
@@ -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
|
||||
@@ -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]
|
||||
@@ -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
|
||||
@@ -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<Tag>: 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<Tag>: 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<Tag> (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<Tag> (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]
|
||||
@@ -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
|
||||
@@ -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 | [email protected]]
|
||||
|
||||
== Queries
|
||||
-- from Member m where m.email = :e (e = new Email("[email protected]"))
|
||||
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[[email protected]]]
|
||||
|
||||
== 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]
|
||||
@@ -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'
|
||||
@@ -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 <unzipped jar> | wc -l
|
||||
0
|
||||
$ grep -rl 'hibernate.use_nationalized_character_data' <unzipped jar> | wc -l # control: a real setting is found
|
||||
3
|
||||
@@ -0,0 +1,65 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.ankurm</groupId>
|
||||
<artifactId>embeddables</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>embeddables</name>
|
||||
<description>Records and value objects in Hibernate 7: @Embeddable records, null handling, collections of embeddables, equality and DDD value objects (plain Hibernate on H2)</description>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Newest 7.x GA in maven-metadata.xml on 2026-11-26 (8.0.0.CR1 is listed after it, but CR1 is not GA). -->
|
||||
<hibernate.version>7.4.17.Final</hibernate.version>
|
||||
<persistence.version>3.2.0</persistence.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.persistence</groupId>
|
||||
<artifactId>jakarta.persistence-api</artifactId>
|
||||
<version>${persistence.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>2.4.240</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>6.0.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.27.7</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<argLine>-Xmx512m</argLine>
|
||||
<systemPropertyVariables>
|
||||
<h.version>${hibernate.version}</h.version>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+8
@@ -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
|
||||
Executable
+19
@@ -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#.*<hibernate.version>\(.*\)</hibernate.version>.*#\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 <unzipped jar> | wc -l"
|
||||
echo "$(grep -rl -a 'create_empty_composites' "$TMP" | wc -l)"
|
||||
echo "\$ grep -rl 'hibernate.use_nationalized_character_data' <unzipped jar> | 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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.ankurm.embeddables;
|
||||
|
||||
import jakarta.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public record Address(String street, String city, String zip, Geo geo) {
|
||||
}
|
||||
@@ -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<Tag> tagSet = new LinkedHashSet<>();
|
||||
|
||||
@ElementCollection
|
||||
public List<Tag> tagBag = new ArrayList<>();
|
||||
|
||||
/** NOT NULL components: Hibernate can delete one element by its own columns. */
|
||||
@ElementCollection
|
||||
public Set<NnTag> strictSet = new LinkedHashSet<>();
|
||||
|
||||
@ElementCollection
|
||||
@OrderColumn
|
||||
public List<Tag> tagOrdered = new ArrayList<>();
|
||||
|
||||
protected Article() {
|
||||
}
|
||||
|
||||
public Article(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.ankurm.embeddables;
|
||||
|
||||
import jakarta.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public record Tag(String name, String colour) {
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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<String> sql = new CopyOnWriteArrayList<>();
|
||||
final SessionFactory sf;
|
||||
List<String> last = List.of();
|
||||
|
||||
Db(Class<?>... entities) {
|
||||
this(Map.of(), entities);
|
||||
}
|
||||
|
||||
Db(Map<String, String> 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<String> rows(String query) {
|
||||
List<String> 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<String> 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<String> 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<Session, Object> 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<Session> work) {
|
||||
inTx(s -> {
|
||||
work.accept(s);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
<R> R inTx(Function<Session, R> 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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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.<java.util.Collection<Tag>>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<Tag>: 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<Tag>: 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<Tag> (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<Tag> (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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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("[email protected]"))));
|
||||
t.line("stored value: " + db.rows("select * from member"));
|
||||
assertThat(db.rows("select * from member").get(0)).contains("[email protected]");
|
||||
|
||||
t.heading("Queries");
|
||||
db.step(t, "from Member m where m.email = :e (e = new Email(\"[email protected]\"))", s -> s.createSelectionQuery("from Member m where m.email = :e", Member.class)
|
||||
.setParameter("e", new Email("[email protected]")).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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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<String> sql) {
|
||||
line("-- " + label);
|
||||
if (sql.isEmpty()) {
|
||||
line(" (no SQL)");
|
||||
}
|
||||
for (String s : sql) {
|
||||
line(" sql> " + s);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
void write() {
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, lines);
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user