Embedded value objects with @Embeddable
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's address is line1, city, state and pincode, always used together. Passing four loose strings everywhere invites mix-ups, while a separate table for four columns would be too much.
Value object vs entity
A value object is a small type defined only by its values, with no id of its own. Two postal addresses with the same line1, city, state and pincode are the same address.
Example 1 compares two kinds of object: a value object, which is equal when its values match, and an entity, which is equal when its id matches.
Example 1 · A value object and an entity in plain Java
import java.util.Objects;
// A value object: no id, defined only by its values, never changed after creationrecord PostalAddress(String line1, String city, String state, String pincode) {}
// An entity: has its own id; two customers with the same name are still two customersclass Customer { private final int id; private final String fullName; private PostalAddress home;
Customer(int id, String fullName, PostalAddress home) { this.id = id; this.fullName = fullName; this.home = home; }
void moveTo(PostalAddress newHome) { this.home = newHome; // replace the whole value, never edit it }
PostalAddress home() { return home; }
@Override public boolean equals(Object o) { return o instanceof Customer other && id == other.id; }
@Override public int hashCode() { return Objects.hash(id); }
@Override public String toString() { return "Customer " + id + " (" + fullName + ")"; }}
public class ValueVsEntityDemo {
public static void main(String[] args) { PostalAddress hostelA = new PostalAddress("Room 214, Girls Hostel, COEP", "Pune", "Maharashtra", "411005"); PostalAddress hostelB = new PostalAddress("Room 214, Girls Hostel, COEP", "Pune", "Maharashtra", "411005"); System.out.println("Same address values -> equal? " + hostelA.equals(hostelB));
Customer priya = new Customer(5, "Priya Sharma", hostelA); Customer otherPriya = new Customer(9, "Priya Sharma", hostelB); System.out.println("Same name, different ids -> equal? " + priya.equals(otherPriya));
priya.moveTo(new PostalAddress("9 Karve Road, Kothrud", "Pune", "Maharashtra", "411038")); System.out.println(priya + " now lives at " + priya.home().line1()); System.out.println("Still the same customer? " + priya.equals(new Customer(5, "Priya S", null))); }}Same address values -> equal? true Same name, different ids -> equal? false Customer 5 (Priya Sharma) now lives at 9 Karve Road, Kothrud Still the same customer? true
What this code does
- Two
PostalAddressrecords with the same four values are equal: a record'sequalscompares every component, which is exactly the meaning of a value object. Customercompares only ids. Same name with different ids gives two customers; a changed name and address with the same id is still customer 5.moveToreplaces the whole address. A value object is never edited field by field.
Money amounts, pincodes and date ranges are value objects too. An entity has an identity of its own, its id: two customers named "Priya Sharma" are still two customers, and a customer who moves house is still the same customer.
The question to ask: does anything need to point at this thing by its id, or track it over time? If yes, it is an entity with its own table. If it only describes something else, it is a value object, and in JPA a value object becomes an @Embeddable.
A PostalAddress @Embeddable inside ShopLite's Address
@Embeddable marks a class whose fields are stored in the table of the entity that uses it, and @Embedded marks the entity field of that type. The columns stay in the same row; only the Java side is grouped.
PostalAddress holds line1, city, state and pincode, and Address has one @Embedded field of that type. Example 2 shows both classes.
Example 2 · PostalAddress.java (@Embeddable) and Address.java (@Embedded)
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
// src/main/java/com/shoplite/customer/PostalAddress.javapackage com.shoplite.customer;
import jakarta.persistence.Column;import jakarta.persistence.Embeddable;
import java.util.Objects;
@Embeddablepublic class PostalAddress {
@Column(nullable = false, length = 150) private String line1;
@Column(nullable = false, length = 60) private String city;
@Column(nullable = false, length = 60) private String state;
@Column(nullable = false, length = 6) private String pincode;
protected PostalAddress() { }
public PostalAddress(String line1, String city, String state, String pincode) { this.line1 = line1; this.city = city; this.state = state; this.pincode = pincode; }
public String getLine1() { return line1; } public String getCity() { return city; } public String getState() { return state; } public String getPincode() { return pincode; }
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PostalAddress other)) return false; return line1.equals(other.line1) && city.equals(other.city) && state.equals(other.state) && pincode.equals(other.pincode); }
@Override public int hashCode() { return Objects.hash(line1, city, state, pincode); }
@Override public String toString() { return line1 + ", " + city + ", " + state + " " + pincode; }}
// src/main/java/com/shoplite/customer/Address.javapackage com.shoplite.customer;
import jakarta.persistence.Column;import jakarta.persistence.Embedded;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
@Entity@Table(name = "addresses")public class Address {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "address_id") private Integer id;
@Column(name = "customer_id", nullable = false) private Integer customerId;
@Column(nullable = false, length = 20) private String label;
@Embedded private PostalAddress postalAddress; // line1, city, state, pincode live in this table
@Column(name = "is_default", nullable = false) private boolean defaultAddress;
protected Address() { }
public Address(Integer customerId, String label, PostalAddress postalAddress) { this.customerId = customerId; this.label = label; this.postalAddress = postalAddress; }
public Integer getId() { return id; } public String getLabel() { return label; } public PostalAddress getPostalAddress() { return postalAddress; } public boolean isDefaultAddress() { return defaultAddress; }}
package com.shoplite.customer;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentclass AddressDemoRunner implements CommandLineRunner {
private final AddressRepository addresses;
AddressDemoRunner(AddressRepository addresses) { this.addresses = addresses; }
@Override public void run(String... args) { Address home = addresses.findById(1).orElseThrow(); System.out.println(home.getLabel() + ": " + home.getPostalAddress());
PostalAddress hostel = new PostalAddress("Block C, IIT Bombay", "Mumbai", "Maharashtra", "400076"); Address saved = addresses.save(new Address(8, "Hostel", hostel)); System.out.println("Saved address " + saved.getId() + " in " + saved.getPostalAddress().getCity());
Address work = addresses.findById(2).orElseThrow(); PostalAddress sameAsWork = new PostalAddress("Prestige Tech Park, Marathahalli", "Bengaluru", "Karnataka", "560103"); System.out.println("Same place as Work? " + work.getPostalAddress().equals(sameAsWork)); }}DEBUG ... org.hibernate.SQL : select a1_0.address_id,a1_0.customer_id,a1_0.is_default,a1_0.label,a1_0.city,a1_0.line1,a1_0.pincode,a1_0.state from addresses a1_0 where a1_0.address_id=? Home: 12 MG Road, Indiranagar, Bengaluru, Karnataka 560038 DEBUG ... org.hibernate.SQL : insert into addresses (customer_id,is_default,label,city,line1,pincode,state) values (?,?,?,?,?,?,?) Saved address 10 in Mumbai DEBUG ... org.hibernate.SQL : select a1_0.address_id,a1_0.customer_id,a1_0.is_default,a1_0.label,a1_0.city,a1_0.line1,a1_0.pincode,a1_0.state from addresses a1_0 where a1_0.address_id=? Same place as Work? true
What this code does
- One
SELECTonaddressesreads all columns; Hibernate putscity,line1,pincodeandstateinto aPostalAddressand the rest intoAddress. There is no join and no extra table. - The
INSERTwrites the four embedded columns in the same row, taken fromhostel. - Because
PostalAddresscompares values, a newly typed address equals the stored "Work" address: useful for "deliver to an address you already saved?" checks. This class version needs a no-arg constructor and hand-writtenequals/hashCode.
In the database nothing changes: addresses still has the four columns, and the SELECT and INSERT list the embedded columns next to the entity's own (Example 2). ShopLite's Address stays an entity, because orders refer to it by address_id and the API reads it at /customers/{id}/addresses/{addressId}. The postal part is the value object, so code that prints a label or checks a delivery pincode passes one PostalAddress instead of four strings.
protected) and fields Hibernate can set. Records are the exception (fourth section).@Embedded with @AttributeOverride
@AttributeOverride changes the column that one field of an embeddable maps to, for this one use. name is the field inside the embeddable and column is the new column.
A courier booking has a pickup place and a drop place, both of the same Place type. Example 3 gives each its own column names.
Example 3 · One embeddable twice: pickup and drop places
Runs in: the mapping-lab practice project with a throwaway lab database (ddl-auto=create)
// src/main/java/com/shoplite/lab/Place.javapackage com.shoplite.lab;
import jakarta.persistence.Embeddable;
@Embeddablepublic record Place(String line1, String city, String pincode) {}
// src/main/java/com/shoplite/lab/CourierBooking.javapackage com.shoplite.lab;
import jakarta.persistence.AttributeOverride;import jakarta.persistence.Column;import jakarta.persistence.Embedded;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
@Entity@Table(name = "courier_bookings")public class CourierBooking {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id;
@Embedded @AttributeOverride(name = "line1", column = @Column(name = "pickup_line1")) @AttributeOverride(name = "city", column = @Column(name = "pickup_city")) @AttributeOverride(name = "pincode", column = @Column(name = "pickup_pincode")) private Place pickup;
@Embedded @AttributeOverride(name = "line1", column = @Column(name = "drop_line1")) @AttributeOverride(name = "city", column = @Column(name = "drop_city")) @AttributeOverride(name = "pincode", column = @Column(name = "drop_pincode")) private Place drop;
protected CourierBooking() { }
public CourierBooking(Place pickup, Place drop) { this.pickup = pickup; this.drop = drop; }
public Integer getId() { return id; } public Place getPickup() { return pickup; } public Place getDrop() { return drop; }}
// src/main/java/com/shoplite/lab/CourierDemoRunner.javapackage com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentclass CourierDemoRunner implements CommandLineRunner {
private final CourierBookingRepository bookings;
CourierDemoRunner(CourierBookingRepository bookings) { this.bookings = bookings; }
@Override public void run(String... args) { Place hostel = new Place("Room 214, Girls Hostel, COEP", "Pune", "411005"); Place home = new Place("9 Karve Road, Kothrud", "Pune", "411038"); CourierBooking booking = bookings.save(new CourierBooking(hostel, home));
CourierBooking loaded = bookings.findById(booking.getId()).orElseThrow(); System.out.println("From " + loaded.getPickup().city() + " " + loaded.getPickup().pincode() + " to " + loaded.getDrop().city() + " " + loaded.getDrop().pincode()); }}DEBUG ... org.hibernate.SQL : create table courier_bookings (id integer not null auto_increment, drop_city varchar(255), drop_line1 varchar(255), drop_pincode varchar(255), pickup_city varchar(255), pickup_line1 varchar(255), pickup_pincode varchar(255), primary key (id)) engine=InnoDB DEBUG ... org.hibernate.SQL : insert into courier_bookings (drop_line1,drop_city,drop_pincode,pickup_line1,pickup_city,pickup_pincode) values (?,?,?,?,?,?) DEBUG ... org.hibernate.SQL : select cb1_0.id,cb1_0.drop_line1,cb1_0.drop_city,cb1_0.drop_pincode,cb1_0.pickup_line1,cb1_0.pickup_city,cb1_0.pickup_pincode from courier_bookings cb1_0 where cb1_0.id=? From Pune 411005 to Pune 411038 The same entity without the six @AttributeOverride lines: Caused by: org.hibernate.MappingException: Column 'line1' is duplicated in mapping for entity 'com.shoplite.lab.CourierBooking' (use '@Column(insertable=false, updatable=false)' when mapping multiple properties to the same column)
What this code does
- Each
@AttributeOverriderenames one field ofPlacefor one use, so the table getspickup_*anddrop_*columns, six in all. - Without overrides, both embedded fields claim
line1,cityandpincode, and Hibernate refuses to start. Its hint aboutinsertable=falseis for a different case (two fields sharing one column on purpose); here the fix is overrides. Placeis a record, which the next section explains.
@AttributeOverride(name = "city", column = @Column(name = "pickup_city")) renames one column. You need it when the table's column names differ from the embeddable's, and always when one entity embeds the same type twice: without overrides both fields map to line1, city and pincode, and Hibernate stops at startup with Column 'line1' is duplicated in mapping for entity (Example 3).
The annotation can be repeated on the field (Java 8+), as in the example. Older code wraps the repeats in @AttributeOverrides({ ... }); both mean the same.
ddl-auto: create). It is not part of ShopLite.Records as embeddables
A Java record can be an @Embeddable in Hibernate 6.2 and later, including Hibernate 7. Example 4 maps PostalAddress as a record.
Example 4 · PostalAddress as a record, with a Pincode inside
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
// src/main/java/com/shoplite/customer/PostalAddress.javapackage com.shoplite.customer;
import com.shoplite.common.Pincode;import jakarta.persistence.Column;import jakarta.persistence.Embeddable;
@Embeddablepublic record PostalAddress( @Column(nullable = false, length = 150) String line1, @Column(nullable = false, length = 60) String city, @Column(nullable = false, length = 60) String state, @Column(nullable = false, length = 6) Pincode pincode) {
@Override public String toString() { return line1 + ", " + city + ", " + state + " " + pincode; }}
// src/main/java/com/shoplite/customer/AddressDemoRunner.javapackage com.shoplite.customer;
import com.shoplite.common.Pincode;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentclass AddressDemoRunner implements CommandLineRunner {
private final AddressRepository addresses;
AddressDemoRunner(AddressRepository addresses) { this.addresses = addresses; }
@Override public void run(String... args) { Address home = addresses.findById(1).orElseThrow(); System.out.println(home.getLabel() + ": " + home.getPostalAddress()); System.out.println("City: " + home.getPostalAddress().city());
PostalAddress hostel = new PostalAddress("Block C, IIT Bombay", "Mumbai", "Maharashtra", new Pincode("400076")); Address saved = addresses.save(new Address(8, "Hostel", hostel)); System.out.println("Saved address " + saved.getId() + ": " + saved.getPostalAddress());
PostalAddress copy = new PostalAddress("Block C, IIT Bombay", "Mumbai", "Maharashtra", new Pincode("400076")); System.out.println("Equal by value? " + hostel.equals(copy)); }}DEBUG ... org.hibernate.SQL : select a1_0.address_id,a1_0.customer_id,a1_0.is_default,a1_0.label,a1_0.line1,a1_0.city,a1_0.state,a1_0.pincode from addresses a1_0 where a1_0.address_id=? Home: 12 MG Road, Indiranagar, Bengaluru, Karnataka 560038 City: Bengaluru DEBUG ... org.hibernate.SQL : insert into addresses (customer_id,is_default,label,line1,city,state,pincode) values (?,?,?,?,?,?,?) Saved address 10: Block C, IIT Bombay, Mumbai, Maharashtra 400076 Equal by value? true
What this code does
- The 18-line record replaces the 55-line class version: no no-arg constructor, no getters (
city()is generated), no hand-writtenequals.Addressdid not change at all. - Columns now appear in component order (
line1, city, state, pincode). ThePincodeconverter from the previous lesson is applied inside the embeddable automatically. - Two records with the same values are equal, which is the value-object meaning, for free.
A record fits a value object perfectly: no id, fields that cannot change, and equals, hashCode and toString that use all values for free. Hibernate creates it through its canonical constructor, the one with all components, so checks in a compact constructor also run when a row is loaded. @Column goes on the record components.
ShopLite uses this shape: record PostalAddress(String line1, String city, String state, Pincode pincode), with the Pincode converter from the enums, dates and money lesson working inside the embeddable. Records still cannot be entities; the difference is that an embeddable is never proxied or changed in place.
When every embedded column is NULL
An embedded object whose columns are all NULL is loaded as null, not as an object full of null fields. Example 5 shows the trap.
Example 5 · Every embedded column NULL: the object loads as null
Runs in: the mapping-lab practice project with a throwaway lab database (ddl-auto=create)
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentclass CourierDemoRunner implements CommandLineRunner {
private final CourierBookingRepository bookings;
CourierDemoRunner(CourierBookingRepository bookings) { this.bookings = bookings; }
@Override public void run(String... args) { Place hostel = new Place("Room 214, Girls Hostel, COEP", "Pune", "411005"); Place unknown = new Place(null, null, null); // every field empty CourierBooking booking = bookings.save(new CourierBooking(hostel, unknown)); System.out.println("In memory after save, drop = " + booking.getDrop());
CourierBooking loaded = bookings.findById(booking.getId()).orElseThrow(); System.out.println("After loading, drop = " + loaded.getDrop());
try { System.out.println(loaded.getDrop().city()); } catch (NullPointerException e) { System.out.println("NullPointerException: the drop place is null, not an empty Place"); } }}DEBUG ... org.hibernate.SQL : insert into courier_bookings (drop_line1,drop_city,drop_pincode,pickup_line1,pickup_city,pickup_pincode) values (?,?,?,?,?,?) In memory after save, drop = Place[line1=null, city=null, pincode=null] DEBUG ... org.hibernate.SQL : select cb1_0.id,cb1_0.drop_line1,cb1_0.drop_city,cb1_0.drop_pincode,cb1_0.pickup_line1,cb1_0.pickup_city,cb1_0.pickup_pincode from courier_bookings cb1_0 where cb1_0.id=? After loading, drop = null NullPointerException: the drop place is null, not an empty Place
What this code does
- The saved object still holds the empty
Place, because Hibernate keeps using the object you gave it. - The
findByIdreads threeNULLcolumns fordropand returnsnullfor the whole embeddable, sogetDrop().city()throws. - The bug hides in a test that never reloads. Make the columns
NOT NULL, or treat the embedded value as optional in every caller.
Hibernate has no way to tell "no address" from "an address with nothing in it", so it chooses null. You save new Place(null, null, null) and your test works, because the object in memory is still the empty Place. The next load gives null, and booking.getDrop().city() throws NullPointerException.
Two safe designs: make the columns NOT NULL, as ShopLite's address columns are, so an empty embeddable can never be saved; or treat the embedded field as optional everywhere, for example a getter that returns Optional<Place>.
Order of execution
Follow the empty Place
Put the steps in the order they happen.
Next step
Check your understanding
11 quick questions