Skip to main content

Overview

Mappers are responsible for transforming data between your domain model (Entities, Aggregates, Value Objects) and your persistence layer (database records). They keep your domain clean and independent of database concerns.

Why Use Mappers?

Separation of Concerns

Domain models stay focused on business logic, not database schema

Schema Independence

Change database schema without touching domain code

Data Transformation

Handle type conversions, naming conventions, and structure differences

Testability

Test domain logic without database dependencies

The Mapper Base Class

The base class is simple - implement build() to transform from Input to Output. Use buildMany() to transform arrays.

Creating Mappers

Domain to Persistence

Transform domain entities to database records:

Persistence to Domain

Transform database records to domain entities:

Handling Complex Structures

Nested Entities

Value Objects

When nested entities are stored in separate tables:

Type Conversions

Common conversions between domain and persistence:

Id ↔ String

Enum ↔ String

Date Handling

JSON Fields

Nullable Relations

Mapper Composition

Compose mappers for complex aggregates:

Mapping Lists

The base Mapper class includes a buildMany() method for transforming arrays:

Using with Repository

Testing Mappers