Course contentsShow
← Software Engineering
Lesson 936 of 1,93329. Object-Relational MappingFree lesson

Data Mapper Pattern

Separating domain objects from persistence logic using a mapper layer to translate between them.

Data Mapper Pattern

What you'll learn: How to keep your domain objects blissfully unaware of database details by introducing a dedicated mapper layer between them.

The Core Idea

The Data Mapper Pattern separates your domain objects (your business logic classes) from persistence concerns by creating a mapper layer that handles all database interactions. Unlike the Active Record pattern where objects know how to save themselves, here your domain objects remain "ignorant" of the database—they're just plain objects focused on business logic.

Think of it like a translator at a conference: your domain objects speak "business language," the database speaks "SQL," and the mapper translates between them. Your User object doesn't know it lives in a users table—it just holds data and behavior. The UserMapper handles all the loading, saving, and querying.

How It Works

The mapper is responsible for:

  • Fetching rows from the database and converting them into domain objects
  • Persisting domain objects by converting them back into database rows
  • Managing all SQL queries and database interactions
  • Tracking which objects have changed and need saving

Your domain objects stay clean and testable because they have zero database dependencies. You can swap the entire persistence layer without touching business logic.

Benefits

This separation means your domain layer can be tested without a database, you can change database schemas without touching domain code, and your business logic stays focused on... business logic. The trade-off? More code to write and maintain compared to Active Record's simplicity.

Key Takeaway: The Data Mapper Pattern isolates domain objects from persistence by delegating all database operations to a separate mapper layer, keeping business logic clean and database-independent.