Skip to main content

Records and Value Objects in Hibernate 7: @Embeddable Records Done Right

How @Embeddable records behave in Hibernate 7.4.17, shown with captured SQL: the all-null rule (a null attribute never reaches your constructor), replace-not-mutate updates, why one removed element rewrites a whole Set, record equals vs database equality, a DDD Email value object, and why a record cannot be an @Entity.

Take a price. In the database it is two columns: amount and currency. In your Java code it is two fields that always travel together, and the day somebody adds 10 to 5 without noticing one is rupees and the other dollars is the day you wish they had been one thing. That one thing has a name: a value object — a small immutable object with no identity of its own, equal to another when all its parts are equal. Java records are almost exactly that, and Hibernate lets you store one inside an entity with @Embeddable. It works well, and it also has a handful of surprises that only show up when you run it: a null that never reaches your constructor, a collection that rewrites every row to remove one, an equals() that disagrees with the database, and a column called value that silently breaks table creation. This article runs each of those against a real Hibernate and shows what happened.
Versions tested. 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 is a candidate release, not GA), Jakarta Persistence 3.2.0 (newest GA; 4.0.0-M8 is a milestone, and 3.2.0 is what the Hibernate 7.4.17 POM depends on), H2 2.4.240, JUnit 6.0.3, Java 25 (Temurin 25.0.5.1 LTS). Plain Hibernate, no Spring. Every SQL line and result below is quoted from a committed transcript written by the test suite in hibernate-demo/embeddables. Only 7.4.17 was tested; nothing here was run on Hibernate 8.

A record is a group of columns with a name

An embeddable is a class whose fields are stored in the owner’s table instead of in a table of its own. The owner — the entity — just declares a field of that type. The embeddable has no @Id and no row of its own; it lives and dies with its owner. A record fits because it has no setters and no natural no-argument constructor, and Hibernate loads it anyway (shown below). Here is the whole mapping. Imports are omitted; the full files are linked.
/** 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) {
}

Source: Money.java. The @Column annotations sit on the record components; the DDL below shows the precision and length taking effect.

@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;
	}
}

Source: Product.java. The protected no-argument constructor is for the entity, which is an ordinary class; the record has none.

An embedded record has no table of its own: its components become columns of the ownerProduct (an @Entity)Long idString nameMoney price (an @Embeddable record)BigDecimal amountString currencytable PRODUCTIDNAMEAMOUNTCURRENCYColumn names carry no price_ prefix.One row, one SELECT, no join: the record is just a named group of columns.

The diagram is the mental model for the rest of the page. Money contributes two columns to PRODUCT, and a load is one SELECT with no join. Notice the column names: they are AMOUNT and CURRENCY, not PRICE_AMOUNT. The attribute name price is not part of the column name, which matters in the third section.

Here is what happened when the test persisted a Product and loaded it back in a new session (from output/01-basic.txt):

== 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
The value changed on the way through the database. The test stored Money(10.5, INR) and read back Money[amount=10.50, currency=INR]. The column is NUMERIC(12,2), so the database returned a BigDecimal with scale 2, and the transcript confirms the original and the loaded record are not equal. This is a BigDecimal property, not a Hibernate bug: BigDecimal.equals compares scale, and so does the record’s generated equals(). If you compare money in Java, compare with compareTo or normalise the scale in the constructor.
Intermediate: how a record gets built, and whether @Embeddable is required A record has exactly one way to be created: its canonical constructor. Hibernate has no other route to an instance, so it must call that constructor when it assembles Money from a result row. This is inference, but the failure shown in the value-object section supports it: when a constructor throws, the exception surfaces wrapped in a Hibernate InstantiationException. The tests also tried a record with no @Embeddable annotation (PlainMoney) used through @Embedded. On 7.4.17 it created the same two columns and round-tripped, shown in output/09-failures.txt. I still annotate every embeddable: it documents intent, and I would not build on the unannotated behaviour without testing it on your version.

Going deeper

You cannot edit a record, so you replace it

A record’s fields are final. To change a price you do not call a setter; you assign a new Money to the entity’s field. Hibernate notices at flush time (when pending changes are sent to the database) that the value differs from the one it loaded and writes an UPDATE. The interesting question is what “differs” means, because the record has its own equals() and the previous section showed that equals() can disagree with the database.

The test replaced the price four ways in four sessions; the full SQL is in output/01-basic.txt:

== 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
Two different questions: are these records equal, and has the row changed?Java: record equals()new Money(12.0, INR) .equals(new Money(12.00, INR))= falseBigDecimal.equals compares scale tooHibernate: dirty check on flushreplace price 12.00 with 12.0 UPDATE issued?= nocompares the attribute values, not equals()The record’s own equals() decides Set membership and map lookups. It does not decide what is written.

Read the diagram against the transcript. Replacing 12.00 with 12.0 produced a record that is not equal to the old one (false), yet Hibernate sent no UPDATE. Replacing 13.00 with an identical new Money(13.00, INR) also sent none. So dirty checking is not calling the record’s equals(); it compares the stored attributes using the rules of each attribute’s type. The practical meaning is good news: a rebuilt-but-same value does not cause a write.

Intermediate: what this means for your own value objects Two separate mechanisms answer two separate questions. The record’s equals()/hashCode() decide whether two Money objects are the same in a HashSet or as a map key. Hibernate’s dirty check decides whether a row needs writing. They agree for strings and integers and disagree for BigDecimal, as the transcript shows. If you want Money(12.0) and Money(12.00) to be equal in Java too, normalise the scale in a compact constructor (amount = amount.setScale(2)) so both questions give the same answer. I did not test that variant; it is the standard remedy, not a measured result.

Going deeper

Using the same record twice needs column overrides

An order has a billing address and a shipping address, both an Address. Because embedded column names do not include the attribute name, both addresses want a column called street, and Hibernate refuses to start. The fix is to rename the second set with @AttributeOverride, one per column, including the columns of a record nested inside it (geo.lat, geo.lon). Here is the mapping that works:
/** 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;
	}
}

Source: Customer.java, with the two records Address.java and Geo.java. The columns it creates, and a load, from output/02-two-uses.txt:

== 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]

And the failure without overrides (BadCustomer.java), from output/09-failures.txt:

== 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)
The error names the problem, but read the hint carefully. The message names the column and the entity. Its suggestion, @Column(insertable=false, updatable=false), is for two properties that intentionally share one column; for two separate addresses you want @AttributeOverride.

The nested Geo shows that records can contain records; the shipping address was stored with no geo and came back with geo=null, which leads straight into null handling.

Going deeper: more on embedding twice Every override replaces one column name, so a nested record means dotted names (geo.lat). With many embedded attributes of the same type the list gets long; a naming strategy is the alternative, but I did not test one here, so treat that as a pointer rather than a result.

Going deeper

What happens when the columns are null

A database column can be null; a record component can be null; and a whole embedded attribute can be null. Hibernate has to map between those, and it picks a simple rule worth memorising: if every column of an embeddable is null, the attribute is null and your constructor is never called. If at least one column has a value, you get a record, and any null columns become null components.
What is in the columns decides whether you get null or a recordamountcurrencyprice after loadingnullnullnull (no record is created, constructor not called)nullINRMoney[amount=null, currency=INR] (constructor sees a null)10.00INRMoney[amount=10.00, currency=INR]A compact constructor that rejects nulls turns the middle row into an exception on load,while the first row still gives plain null. All-or-nothing is only safe if the data is.

The picture shows the three cases the test produced. The top row is the one that surprises people: there is no Money object whose fields are all null; there is just null. The transcript (output/03-nulls.txt) shows each case, plus what the queries look like:

== 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]

Two query details follow from the rule. p.price is null becomes amount is null and currency is null — both must be null — while p.price.amount is null checks one column and also matches the product whose currency is set. They are different questions.

Now a record that refuses nulls (Weight, Weight.java):

/** 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");
	}
}
== 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]
A compact constructor that rejects nulls does not protect you from a null embedded attribute. A Parcel with no weight at all loaded fine, as plain null, because the constructor was never called. But a row with magnitude null and unit set made the load fail. The all-or-nothing guarantee holds only if the table can never hold a half-filled group; add a CHECK constraint if you rely on it. (The component is called magnitude, not value, for a reason explained in the value-object section.)
Intermediate: nested nulls, primitives and a setting that does nothing Nested records. A billing Address whose Geo columns were all null loaded as an Address with geo=null, and a shipping address whose columns were all null loaded as shipping=null. The same all-null rule applies at each level:
== 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
Primitive components. A record such as Dim.java (Dim(int width, int height)) cannot hold null, which suggests NOT NULL columns, and that would make an optional Dim impossible. The test shows otherwise: the DDL made both columns nullable, and a Box with dim = null was stored as two null columns. From output/04-primitives.txt:
== 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]
The column order in the stored rows is alphabetical, so 4 | 3 | 1 is height, width, id. The create_empty_composites setting. Some guides mention hibernate.create_empty_composites.enabled=true as a way to get an empty embeddable instead of null for all-null columns. I tried it: with the setting on, the loaded value was still null for both Money and Weight (the last section of output/03-nulls.txt). A search through every class and resource in the 7.4.17 jar finds no such string, while a control search for a real setting finds three files, so the setting appears not to exist in this version:
# 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
I verified only 7.4.17. Source: scripts/search-setting.sh.

Going deeper

A collection of records: the SQL is not what you expect

To store several records for one entity — a list of tags, say — you use @ElementCollection. Hibernate creates a separate table with the owner’s id plus one column per record component. The records have no identity of their own: Hibernate cannot say “update tag 7” because there is no tag 7. Watch what that costs. This entity maps the same shape four ways:
/** 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;
	}
}

Source: Article.java, with Tag.java (nullable components) and NnTag.java (nullable = false). Each collection held three elements; the test removed one. From output/05-collections.txt:

== 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
Remove one of three elements: what reached the databaseSet, nullable1 delete (all rows)2 inserts3 statementsList (bag)1 delete (all rows)2 inserts3 statementsList + @OrderColumn1 delete (last slot)1 update (shift up)2 statementsSet, NOT NULL1 delete (that row)1 statementCounts are the INSERT/DELETE/UPDATE statements in output/05-collections.txt, not the selects.The only difference between the first and the last box is two nullable=false flags.

The diagram counts only the writes. Removing one tag from a Set<Tag> deleted all three rows and re-inserted the two that stayed. A plain List did the same. With @OrderColumn Hibernate could address rows by position and sent a delete plus an update. Only the Set whose components are nullable = false produced a single targeted DELETE on its own columns. The table definitions in the same transcript show a likely reason: that table has a primary key over all three columns, and the nullable set has none.

== 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
Why this matters. With three tags nobody notices. With 5,000 elements in a collection that is edited often, every single-element change would rewrite 5,000 rows. I did not time that; the transcript proves the statement pattern, not the duration. If a collection can grow, make its components nullable = false, use @OrderColumn, or make the elements a real entity.

Adding an element followed the same pattern in the same file: the nullable Set and the bag deleted every row and re-inserted all three elements, the ordered list sent one insert, and the NOT NULL set sent one insert.

Intermediate: null components and all-null elements inside a collection Collections of records meet the null rule from the previous section in a harsher way. From output/06-collection-nulls.txt (the table columns are ARTICLE_ID, COLOUR, NAME in that order, so 1 | null | java is name “java” with a null colour):
-- 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]
A Tag(null, null) was written to the table as a row of nulls, and when the bag was read back the collection came back empty — an all-null row is indistinguishable from “no element”, and Hibernate drops it. Adding a literal null element to the bag wrote nothing. The rule is the same as for a single attribute: a record whose every column is null does not exist.

Going deeper

Comparing records in queries, and a record as a primary key

You can pass a record as a query parameter and compare an embedded attribute to it. Hibernate turns the comparison into a row-value comparison across the record’s columns. The test also selected the embeddable itself, selected one component, and built a record in a constructor expression. From output/07-equality.txt:
== 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]]

The first query is worth a second look: the parameter was Money(10.0, INR), whose Java equals() says it is different from the stored 10.00 (the equality lines at the top of the same transcript show false), yet the query found product 1. The database compared numbers, not scales. Java equality and SQL equality are two different tests, and the query used the SQL one:

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

A record as a composite key

A record is also a natural composite primary key: it needs equals() and hashCode() by value, which a record gives for free. OrderLineId.java is a two-component record used with @EmbeddedId in OrderLine.java:

/** 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) {
}

Looking it up with a freshly built key, and then twice in one session:

== 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

Both lookups found the row. The second transcript step made two find calls with two different key instances and sent one SELECT; the second call was answered from the session, and the two results were the same object (true). The session matched the keys by value, which is exactly the job of the record’s equals() and hashCode().

Going deeper: equality, keys and what to read next Composite keys make the all-null rule matter in a new way: a key component that is null cannot identify a row, which is why the key columns of OrderLine are NOT NULL in the DDL line of the transcript, even though the record uses wrapper types (Long, Integer).

Going deeper

A real value object: an Email that cannot be invalid

Now put the pieces together as a domain-driven-design value object. Email has one component, validates it, and lower-cases it in the compact constructor, so every Email in memory is valid and normalised. Two emails that differ only in case become equal, and the database never sees the mixed-case form.
/** 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);
	}
}

Source: Email.java. The test stored [email protected] and queried with a different casing. From output/08-value-object.txt:

== 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]]]

Three things to take from this. The stored value is the normalised one. Comparing m.email = :e with an Email parameter works, and because the parameter was normalised by the constructor before it reached the query, mixed-case input matches. And select m.email returns Email records directly.

Now the cost of putting rules in the constructor:

== 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]
The constructor also guards the way back in. It runs when Hibernate loads a row, too. A row containing not-an-address made loading that member fail with Hibernate’s InstantiationException wrapping your IllegalArgumentException, and a query that loads both rows failed as a whole, so one bad row hides the good ones. A query that selected only m.id never built an Email and was fine. The symptom to recognise is Could not instantiate entity ... Email with your own message at the end of the chain; the usual cause is data written before the validation existed, or by another system.
A column called value silently breaks table creation. The natural name for a one-component record is value, and value is a reserved word in H2. The table was never created (its column list is empty), the session factory started anyway, and the first insert failed with “Table not found”. Typing the DDL by hand shows why: H2 rejects value as an identifier. Email therefore maps its component with @Column(name = "email"). From output/09-failures.txt (Handle.java has the bare value); I tried only H2, so other databases may differ, and naming the column yourself is the safe move:
== 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:
Intermediate: keeping validation and legacy data apart If old rows may violate the rule, a constructor that throws is the wrong gate for loading. Two options, neither measured here: clean the data with a migration before shipping the constructor, or load into a looser record and convert it to the strict one in domain code. Choose by how much you trust the table.

Going deeper

What a record cannot be: an entity

Records are values, so it is tempting to make a whole entity a record. RecordEntity.java is exactly that, annotated @Entity, and the surprise is that nothing fails at startup. The table was created and the insert worked. The failure comes later, on the first load. From output/09-failures.txt:
== 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'

Hibernate wrote the row and then could not read it back: No default constructor for entity. Even merge failed, because it begins with a load. An entity needs a no-argument constructor so Hibernate can create a blank instance and fill it, which a record cannot offer. Keep entities as classes and use records for what lives inside them.

Should you even do this? Yes for small, always-together groups of columns that have a rule: money, address, email, date range, coordinates. Their equality is value equality, they have no lifecycle of their own, and a record gives you immutability for free. Think twice when the group needs an id or independent queries (that is an entity), when a collection of them will grow large (see the delete-and-reinsert behaviour above), and when old data may break your constructor on load. And decide deliberately what none of the group looks like: in the database it is all columns null, in Java it is null, and a half-filled group is a state your constructor has to be ready for.

The whole page in one table

QuestionAnswer on Hibernate 7.4.17Transcript
Does a record need a no-arg constructor or setters as an embeddable?No01-basic
Column names for an embedded attributeComponent names only, no attribute prefix01-basic, 02-two-uses
Same record twice in one entityFails with a duplicate column unless overridden02-two-uses, 09-failures
All columns nullAttribute is null, constructor not called03-nulls
Some columns nullRecord with null components03-nulls
Replace with an equal-valued recordNo UPDATE (even when record equals() is false)01-basic
Remove one element: nullable Set or bagDelete all rows, re-insert the rest05-collections
Remove one element: NOT NULL SetOne targeted DELETE05-collections
All-null element in a collectionWritten, but read back as absent06-collection-nulls
Record as @EntityPersists, then fails to load09-failures

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.