Video in progress
In a domain model, entities are linked to each other with a lot of `@OneToMany` and cascade. How do you carry aggregate boundaries into the Hibernate mapping?
I keep cascade and collections only inside a single aggregate: the root manages its own children, and I refer to other aggregates by id, not by object. That sharply reduces the size of the graph, the scope of locks, and accidental cascade mistakes.
📖 Answer
Signs of a bad model: Customer → orders → lines → product → category, all with CascadeType.ALL. One merge(customer) touches hundreds of entities, and remove can delete unexpected things.
I draw a boundary: Order (the root) + OrderLine is one aggregate. They are created together and changed together, and the invariants (total amount, limit) are checked in the root.
@Entity
class Order {
@Id Long id;
Long customerId; // another aggregate: id only
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private final List<OrderLine> lines = new ArrayList<>();
@Version long version;
public void addLine(Long productId, int qty, BigDecimal price) { ... }
}
The benefits:
- the loading boundary is clear: with an Order, only its lines come along;
@Versionis on the root, and every change in the lines must also increment the root's version (OPTIMISTIC_FORCE_INCREMENT, or a field change on the root), so you get a consistent lock across the aggregate;- one transaction changes one aggregate; the others are updated through a domain event.
The cost: if the screen needs the customer's name, you do the join through the read model (a DTO query), not through entity navigation. Sometimes I keep a @ManyToOne(fetch = LAZY) just for reading, but I never put a cascade on it.
In an existing project I do this step by step: first I narrow the cascades, then I remove the collections that cause the most trouble and replace them with repository queries.
Sign up to mark studied questions and save your progress.