Video in progress

When are @Embeddable and @Embedded used?

They let you place a value object inside an entity without a separate table or its own id. The fields of the @Embeddable class become columns in the owner's table, for example Address or Money.

📖 Answer

@Embeddable
public class Address {
    private String city;
    private String street;
    private String zip;
}

@Entity
public class Customer {
    @Id @GeneratedValue
    private Long id;

    @Embedded
    private Address address;   // columns city, street, zip in the customers table
}

If one entity has two of the same type, the column names collide. You rename them with @AttributeOverrides:

@Embedded
@AttributeOverrides({
    @AttributeOverride(name = "city", column = @Column(name = "billing_city")),
    @AttributeOverride(name = "street", column = @Column(name = "billing_street")),
    @AttributeOverride(name = "zip", column = @Column(name = "billing_zip"))
})
private Address billingAddress;

Why this is useful: the code is clearer, and validation and logic (Money.add) live in one place. An embeddable has no lifecycle of its own: it is saved and deleted together with its owner.

Since Hibernate 6.2 you can use a record as an embeddable too.

If all the columns are null, Hibernate usually reads the whole embedded field as null. Be ready for that in your code.