Video in progress
Should you strip the domain model completely of Spring and JPA annotations (hexagonal/clean architecture)? How do you decide?
For a complex, long-lived domain with a lot of business logic the separation pays off; in plain CRUD services it just multiplies mapping and layers with little benefit. I decide based on domain complexity, team size and how fast things change.
📖 Answer
"Always yes" and "always no" are both wrong answers here. You have to look at the cost on both sides.
What full separation gives you:
- Domain classes are tested without a framework, in milliseconds.
- JPA constraints (the empty constructor, mutable fields, lazy proxies) don't affect the domain design.
- Swapping persistence (JPA → jOOQ, or moving part of it to another storage) doesn't touch the domain code.
The cost:
- Two models and a mapper for every entity:
Order(domain) andOrderEntity(JPA). Every new field means a change in three places. - JPA's strengths, dirty checking, lazy loading and optimistic locking, have to be managed by hand inside the adapter.
- For new developers the question "where does this live?" comes up more often.
My practical approach:
- A package boundary, always.
domain,application,infrastructure,web. I lock in the direction of dependencies with an ArchUnit test:noClasses().that().resideInAPackage("..domain..") .should().dependOnClassesThat().resideInAPackage("..web..") .check(classes); - JPA annotations on the domain entity are an acceptable compromise in most cases. They are only metadata, and that is enough as long as the service logic isn't tied to Spring.
- Spring annotations (
@Service,@Transactional) stay in the application layer, not on domain objects. - Full separation only for the core domain with lots of complex rules (lending, pricing, accounting). The CRUD modules around it stay simple.
The decision criteria: how complex the business rules are, how many years the code will live, how many teams touch it, whether persistence can really change. Architecture should exist to lower the cost of change, not to be "pretty".
Sign up to mark studied questions and save your progress.