Friday, 9 August 2013

Foreign Key Mapping 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 Foreign Key Mapping Design Pattern?

The Foreign Key Mapping Pattern is one of the key Object-Relational Structural Patterns defined in Martin Fowler's classic book, Patterns of Enterprise Application Architecture (PofEAA).

The Core Definition: It maps an association between objects to a foreign key reference between relational database tables.

In object-oriented design, entities refer to other entities directly via object references or collections (like a List or Set). However, in relational databases, relationships are maintained strictly by placing the primary key of one table as a foreign key column in another table. The Foreign Key Mapping pattern bridges this exact difference.

Real-World Example: Person and Address (1-to-Many Relationship)

Consider a database schema with two tables representing a One-to-Many relationship where one person can have multiple addresses:

  • Person Table: Columns are person_id (Primary Key), name, age, and gender.
    Row 1: id: 1, name: "Joe", age: 23, gender: "Male"
    Row 2: id: 2, name: "Goni", age: 28, gender: "Female"
  • Address Table: Columns are address_id (Primary Key), person_id (Foreign Key referencing Person), and city.
    Joe's addresses: Bangalore, Chennai, and Delhi (all pointing to person_id = 1).
    Goni's addresses: Mumbai and Kerala (both pointing to person_id = 2).

How to Represent This in Java Classes

To represent this database relationship cleanly in object-oriented code, we define two classes:

// Person Class holding a Collection of Addresses
public class Person {
    private Long personId;
    private String name;
    private int age;
    private String gender;
    private Set<Address> addresses = new HashSet<>();

    // Getters and Setters
}

// Address Class referencing the parent Person
public class Address {
    private Long addressId;
    private String city;
    private Person person;

    // Getters and Setters
}

Key Advantages of Foreign Key Mapping

  • Natural Object Navigation: In code, developers can traverse seamlessly from a Person to their list of Address objects without manually writing SQL JOIN queries everywhere.
  • Preserves Referential Integrity: Enforces standard relational constraints in the database using foreign keys while maintaining clean domain models.
  • Powers Modern ORM Frameworks: Forms the core mechanism behind annotations like @OneToMany and @ManyToOne in JPA and Hibernate.

Recommended Design Pattern Tutorials:


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

Click the below Image to Enlarge
Foreign Key Mapping Design Pattern














See also:

  • All Design Patterns Links
  • No comments:

    Post a Comment

    Tutorials