Video in progress
How do you model the difference between an entity and a value object in JPA? When `@Embeddable`, when a separate table?
Something with its own lifecycle and identity is an entity with its own table. Something that is just a part of its owner and is compared by value is an @Embeddable, living as columns in the owner's table.
📖 Answer
The question is: "do I need to refer to this from elsewhere by ID? Does it change separately from its owner?"
@Embeddable
public record Address(String region, String city, String street) {}
@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
@Embedded
private Address address; // region, city, street columns in the customer table
public void moveTo(Address newAddress) { this.address = newAddress; } // replaced as a whole
}
You don't edit a value object in place (address.setCity(...)), you put in a new one. That way Hibernate's dirty checking works correctly, and an address change becomes one clear operation.
If you need a list of value objects, use @ElementCollection. There is one catch: Hibernate gives it no identifier, so even if one element changes it often deletes the whole collection and writes it again. That's fine for 5–10 elements and bad for thousands. In that case it's better to make the thing an entity and work with @OneToMany, even if from the domain point of view it is a value.
When it's an entity:
- something outside refers to it (
OrderLine→Product); - you need to keep its history or audit it separately;
- it can belong to several owners.
When it's an embeddable: Money, Address, Period, PersonName. They never live on their own.
Sign up to mark studied questions and save your progress.