Friday, 9 August 2013

Identity Field Design Pattern

🚀 Master Enterprise Java & Architecture Patterns!

Subscribe to Ram N Java for clean, simple, and beginner-friendly programming tutorials!

🔔 Subscribe Now

What is the Identity Field Design Pattern?

The Identity Field Pattern is one of the essential Object-Relational Structural Patterns described in Martin Fowler's classic book, Patterns of Enterprise Application Architecture (PofEAA).

In enterprise systems, relational databases and object-oriented programming languages determine identity in different ways:

  • Relational Databases: Identify rows uniquely using primary keys (like auto-increment IDs).
  • In-Memory Objects: Identify objects by their memory address or reference equality (like == in Java).

The Core Idea: An Identity Field solves this mismatch by saving a database ID field inside an in-memory object, maintaining exact identity and alignment between an in-memory object and a corresponding database row.

Real-World Example: Person Table and Object Mapping

Consider a database table named Person with columns: id, name, age, and gender.

  • Row 1: id: 1, name: "John", age: 23, gender: "Male"
  • Row 2: id: 2, name: "Goni", age: 28, gender: "Female"

When mapping these rows into a domain class in Java, you define an entity class containing matching fields:

public class Person {
    private Long id;       // Identity Field (Primary Key)
    private String name;
    private int age;
    private String gender;

    // Constructors, Getters & Setters
}

When you load Row 1 into memory, you instantiate a Person object where person1.getId() == 1. When you load Row 2, person2.getId() == 2. Because the database ID lives directly inside the object, your application always knows exactly which row to update or query.

Why Use the Identity Field Pattern?

  • Accurate Persistence: When persisting changes back to the database, the system executes an UPDATE matching the exact primary key without ambiguity.
  • Foundation for Identity Map: Enables an in-memory cache (Identity Map) to verify if an entity has already been fetched by checking its ID.
  • Decoupled Object References: Lets you associate dependent child records or foreign keys cleanly across different tables.

Recommended Design Pattern Tutorials:


Click here to watch in Youtube : https://www.youtube.com/watch?v=fkxfjtCSJiI

Click the below Image to Enlarge
Identity Field Design Pattern















See also:

  • All Design Patterns Links
  • No comments:

    Post a Comment

    Tutorials