Identity Map Pattern
What you'll learn: How to ensure only one in-memory instance exists for each database row, eliminating duplicate objects and data inconsistencies.
The Problem
Imagine you fetch user #42 from the database, then moments later another part of your code fetches user #42 again. Without an identity map, you now have two separate objects representing the same row. If one object gets modified, the other remains unchanged—a recipe for confusion and bugs.
What the Identity Map Does
The Identity Map Pattern maintains a cache of all objects loaded from the database during a session (often tied to a Unit of Work). Before creating a new object from a database row, you check the identity map first. If an object with that primary key already exists, you return the existing instance instead of creating a duplicate.
This solves the identity mismatch problem discussed earlier: ensuring object identity (=== reference equality) aligns with database identity (same primary key).
How It Works
Think of the identity map as a dictionary where:
- Key: The combination of entity type and primary key (e.g.,
"User:42") - Value: The actual object instance
When you load an entity:
- Check if
identity_map["User:42"]exists - If yes, return that cached instance
- If no, load from database, store in map, then return
This pattern is often implemented within a Data Mapper or Repository, working hand-in-hand with the Unit of Work to track changes to these unique instances.
Benefits
- Prevents duplicate object instances
- Maintains referential integrity across your application
- Improves performance by avoiding redundant database queries
- Simplifies change tracking (since all code references the same object)
Key Takeaway: The Identity Map Pattern ensures each database row maps to exactly one in-memory object during a session, eliminating duplicates and maintaining consistent object identity across your application.