✅ Short Answer
In Hibernate/JPA, you map an embeddable object using @Embeddable
on the value class, and @Embedded
on the owning entity’s field → the embeddable’s fields become columns in the entity’s table.
🔎 Detailed Explanation
🔹 Embeddables are reusable value objects:
- They don’t have their own table → they’re embedded into the owning entity’s table.
- Great for grouping related fields (e.g., address, monetary amount, coordinates) into a clean object.
- Avoids cluttering entity classes with dozens of flat fields.
🔹 Steps to map an embeddable
✅ 1) Create the embeddable class
@Embeddable
public class Address {
private String street;
private String city;
private String zipCode;
}
✅ 2) Add the embeddable to an entity
@Entity
public class User {
@Id
private Long id;
private String name;
@Embedded
private Address address; // fields of Address become columns in User table
}
🔹 What happens in the database?
- Hibernate maps
User
into a single table with columns:id
,name
,street
,city
,zip_code
.
🔹 Customizing column names with @AttributeOverrides
If you embed the same embeddable twice or want custom column names, use @AttributeOverrides
:
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "home_street")),
@AttributeOverride(name = "city", column = @Column(name = "home_city")),
@AttributeOverride(name = "zipCode", column = @Column(name = "home_zip"))
})
private Address homeAddress;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "work_street")),
@AttributeOverride(name = "city", column = @Column(name = "work_city")),
@AttributeOverride(name = "zipCode", column = @Column(name = "work_zip"))
})
private Address workAddress;
✅ This allows you to embed the same class multiple times in an entity.
📊 Benefits of Embeddables
✅ Improves code reuse and domain model clarity → avoids repetition.
✅ Keeps the database normalized without creating extra tables.
✅ Supports nested embedding → embeddables can themselves embed other embeddables.
📌 Key Takeaways
✅ Annotate reusable value objects with @Embeddable
, and use @Embedded
in entities.
✅ Embeddables have no separate table → their fields become columns of the owning entity.
✅ Use @AttributeOverrides
to control or disambiguate column names.