Video in progress
Use JPA entities directly as the domain model, or make a separate persistence model: what are the trade-offs?
Using the JPA entity as the domain halves the code, but the domain has to obey Hibernate's rules (a no-arg constructor, proxies, lazy loading). A separate model keeps the domain clean, but adds mapping at every boundary and an extra source of bugs.
📖 Answer
One model (entity = domain):
- less code, Spring Data features work directly;
- dirty checking: you change the aggregate and it's saved when the transaction ends;
- but: you need a
protectedno-arg constructor, you can't usefinalfields,equalsbased ongetClass()breaks because of proxies, and touching a lazy collection outside a transaction gives aLazyInitializationException. Domain code has to know how Hibernate behaves.
A separate model (domain + *JpaEntity + mapper):
- the domain is pure Java: records, immutable values, invariants in the constructor;
- you can change the DB schema without touching the domain;
- but: a mapper for every aggregate, no dirty checking (you call
saveexplicitly), and when updating child collections it's hard to handle orphans and match IDs correctly; - the optimistic lock version also has to be carried between the two models.
My decision is usually:
- central aggregates with complex invariants, and systems whose DB changes independently: a separate model;
- the other 80%: entity = domain, but with discipline: meaningful methods instead of setters, collections returned in an unmodifiable form,
equals/hashCodebased on the ID and proxy-safe.
@Entity
public class Account {
@Id private Long id;
@Version private long version;
private BigDecimal balance;
protected Account() {} // for JPA
public void withdraw(BigDecimal amount) {
if (balance.compareTo(amount) < 0) throw new InsufficientFundsException(id);
balance = balance.subtract(amount);
}
}
The main thing is for the team to pick one approach and write it down. If one module does it one way and another does it differently, the code gets harder to read.
Sign up to mark studied questions and save your progress.