Identity Mismatch: Object Identity vs. Primary Keys
You'll learn how object identity in your application differs fundamentally from database identity, creating subtle but critical challenges in ORM systems.
The Two Faces of Identity
In object-oriented programming, two objects are "the same" if they reference the exact same memory location—this is reference equality. In databases, two rows are "the same" if they share the same primary key value.
This creates a mismatch: your database uses values to identify records, while your application uses memory addresses to identify objects.
The Problem in Practice
Imagine you query the database twice for the same user record (primary key = 123). Without proper ORM handling, you could end up with two distinct objects in memory, both representing the same database row. They have different memory addresses (different object identity) but represent the same logical entity (same database identity).
User object A at memory 0x1A2B → user_id: 123
User object B at memory 0x3C4D → user_id: 123 // Different object, same data!
This causes confusion: if you modify object A, should object B reflect those changes? When comparing A == B using reference equality, they're different—but they represent the same database entity.
Why This Matters
This mismatch leads to cache coherence issues, inconsistent state, and bugs where "the same" user appears as multiple objects. ORMs solve this with identity maps—caches that ensure one primary key maps to one in-memory object during a session.
Key Takeaway: Object identity (memory reference) and database identity (primary key) are fundamentally different concepts; ORMs must bridge this gap to prevent duplicate object representations and maintain consistency.