Video in progress
You need to split the shared Hibernate domain model of a monolith into several services. How do you cut the associations between entities?
First I draw module boundaries inside the monolith and replace the @ManyToOne/@OneToMany associations that cross a boundary with id fields. Cross-module joins become data fetched through an API call or an event. I split the database in stages too: first a separate schema and ownership, then a separate database.
📖 Answer
In a monolith the Hibernate model often turns into an "everything is linked to everything" graph: Order → Customer → Address → Region, Order → Product → Supplier. You cannot split this straight into services, because every service's entity is glued to another service's table with FKs and joins.
I work in stages:
-
Identify the modules inside the monolith (
ordering,catalog,customers) and look at the dependencies. With ArchUnit or Spring Modulith I write a rule like "an entity in the ordering package must not reference a catalog entity": first, stop new links from appearing. -
Replace the associations that cross a boundary with an id:
// before
@ManyToOne(fetch = FetchType.LAZY) private Product product;
// after
@Column(name = "product_id", nullable = false) private Long productId;
private String productNameSnapshot; // the name at the time of the order
This is still one database, and the FK can even stay. But the code no longer relies on chains like order.getProduct().getSupplier(). This is the hardest step: every such join has to be replaced, sometimes with an API, sometimes with a snapshot field, sometimes with a read model.
-
Cross-module queries. Reports often join the tables of several modules. For them I build a separate read model (a table fed by events, or an analytics database via CDC).
-
The database. Each module moves to its own schema, and write access to other modules' tables is removed. Only after that is it safe to deploy a service separately and split the database.
Trade-offs: once you move to ids, the database no longer guarantees referential integrity, so you have to live with events and eventual consistency. Some modules are so tightly coupled that splitting them gains nothing, and leaving them in one service is a valid decision too. I start the split from the question "which part changes on its own and scales on its own", not from the table structure.
Sign up to mark studied questions and save your progress.