Core Concepts
- Entities: Database-focused objects that represent tables/collections
- Domain Models: Business logic containers with rules and behaviors
- DTOs: Data carriers optimized for specific interfaces and operations
1 | Database ⟷ Entities ⟷ Domain Models ⟷ DTOs ⟷ Client/API |
Details
Entities
- Persistence-oriented
- ORM/database annotations
- Database relations and constraints
- Example: UserEntity with JPA annotations mapping to user table
Domain Models
- Business logic-oriented
- Behavior and validation rules
- Independent of persistence mechanisms
- Example: User with methods like isEligibleForDiscount()
DTOs
as described by Martin Fowler in his book “Patterns of Enterprise Application Architecture,” are objects used to carry data.
- Transfer-oriented
- Purpose-specific shapes
- Simple data containers
- Example: UserProfileDto with only public-facing user information
When Data Crosses Boundaries
- Repository Layer: Converts database rows to Entities
- Service Layer: Maps between Entities and Domain Models
- Controller/API Layer: Transforms Domain Models to/from DTOs
Chart
Read Path (Database to Client)
- Database Layer: Raw data exists as rows/documents
- Repository Layer: Converts database rows into Entity objects
- Service Layer: Maps Entities to Domain Models and applies business logic
- Controller/API Layer: Transforms Domain Models to DTOs for external consumption
- Client: Receives serialized DTOs (typically as JSON/XML)
Write Path (Client to Database)
- Client: Sends data (typically JSON/XML)
- Controller/API Layer: Deserializes into DTOs and validates input
- Service Layer: Converts DTOs to Domain Models and applies business rules
- Repository Layer: Transforms Domain Models to Entities
- Database Layer: Persists Entities as database rows/documents