ORMs in Domain-Driven Design
You'll learn how Object-Relational Mappers integrate with Domain-Driven Design principles to preserve domain model integrity while handling persistence.
The Role of ORMs in DDD
In Domain-Driven Design, your domain model represents business concepts and rules—it's the heart of your application. ORMs become your infrastructure layer tool, translating these rich domain objects into database rows and back. The challenge is maintaining domain model integrity while using ORM features.
Repository Pattern Integration
The Repository Pattern serves as the critical bridge. Your domain layer defines repository interfaces expressing what the model needs ("find customer by email"), while ORM-backed implementations live in the infrastructure layer. This keeps persistence concerns out of your domain:
// Domain layer - pure business logic
interface CustomerRepository {
findByEmail(email: string): Customer | null;
save(customer: Customer): void;
}
// Infrastructure layer - ORM implementation
class ORMCustomerRepository implements CustomerRepository {
// Uses ORM features internally
}
Maintaining Domain Integrity
Your domain entities remain focused on business rules, not ORM annotations or mapping concerns. Use the Data Mapper Pattern to keep entities clean—mapping configuration stays external. The Unit of Work Pattern helps manage transactions at the application service level, ensuring domain invariants hold across multiple repository operations.
Think of it like a theater production: your actors (domain objects) focus on the script (business logic), while stagehands (ORM repositories) handle props and scene changes (persistence) behind the curtain. The audience (application services) sees only the performance.
Watch Points
Avoid "anemic domain models" where entities become mere data bags. Keep ORM lazy loading from bleeding into domain logic—eager load what aggregates need. Let repositories return complete, valid domain objects, never half-loaded shells.
Key Takeaway: In DDD, ORMs are infrastructure servants—use them through repositories to persist your domain model without compromising its business-focused purity or invariants.