Core Concepts

  1. Entities: Database-focused objects that represent tables/collections
  2. Domain Models: Business logic containers with rules and behaviors
  3. DTOs: Data carriers optimized for specific interfaces and operations
1
Database ⟷ Entities ⟷ Domain Models ⟷ DTOs ⟷ Client/API

Details

Entities

  1. Persistence-oriented
  2. ORM/database annotations
  3. Database relations and constraints
  4. Example: UserEntity with JPA annotations mapping to user table

Domain Models

  1. Business logic-oriented
  2. Behavior and validation rules
  3. Independent of persistence mechanisms
  4. 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.

  1. Transfer-oriented
  2. Purpose-specific shapes
  3. Simple data containers
  4. 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)

  1. Database Layer: Raw data exists as rows/documents
  2. Repository Layer: Converts database rows into Entity objects
  3. Service Layer: Maps Entities to Domain Models and applies business logic
  4. Controller/API Layer: Transforms Domain Models to DTOs for external consumption
  5. Client: Receives serialized DTOs (typically as JSON/XML)

Write Path (Client to Database)

  1. Client: Sends data (typically JSON/XML)
  2. Controller/API Layer: Deserializes into DTOs and validates input
  3. Service Layer: Converts DTOs to Domain Models and applies business rules
  4. Repository Layer: Transforms Domain Models to Entities
  5. Database Layer: Persists Entities as database rows/documents

Reference: https://medium.com/@lpramithamj/synchronizing-spring-the-artistry-of-data-transfer-objects-dtos-for-effortless-communication-in-3b91697591fc