Showing posts with label ORM. Show all posts
Showing posts with label ORM. Show all posts

Saturday, 14 September 2013

Identity Map 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 Map Design Pattern?

The Identity Map Pattern is a core Object-Relational Behavioral Pattern introduced in Martin Fowler’s classic book, Patterns of Enterprise Application Architecture (PofEAA).

Core Definition: An Identity Map ensures that each object gets loaded only once by keeping every loaded object in a map. When you look for an object, you check the map first to see if it is already loaded.

It acts as an in-memory record registry that maps each database primary key to its corresponding loaded in-memory domain instance during a business transaction.

The Problem: Duplicate In-Memory Objects

Without an Identity Map, loading the same database record multiple times within the same business transaction causes serious issues:

  • Repeated Database Round-trips: Every lookup triggers a redundant SQL SELECT query, wasting database resources.
  • Equivalence Problems: Querying the same row twice creates two separate Java instances in memory. Checking person1 == person2 evaluates to false even though both objects represent the exact same database record.
  • Inconsistent State & Lost Updates: If one part of your code updates person1 and another part modifies person2, one update overwrites the other when written back to the database, resulting in data corruption.

How the Identity Map Works

Whenever a business method or data mapper requests an entity by its ID (e.g., findPerson(101)):

  1. Check Map: The mapper inspects the Identity Map using the ID as the key.
  2. Cache Hit: If the object already exists in the map, it returns that exact cached instance immediately without touching the database.
  3. Cache Miss: If not found, the mapper executes an SQL query, constructs the domain object, registers it in the Identity Map, and returns it.
public class PersonIdentityMap {
    private static Map<Long, Person> knownPersons = new HashMap<>();

    public static Person getPerson(Long id) {
        return knownPersons.get(id);
    }

    public static void addPerson(Person person) {
        knownPersons.put(person.getId(), person);
    }
}

Key Advantages of Using an Identity Map

  • Guarantees Single In-Memory Instance: Ensures that all parts of a transaction share the exact same reference to an entity.
  • Eliminates Redundant SQL Queries: Acts as a first-level transactional cache, boosting application response times.
  • Foundation of Modern ORM Frameworks: Forms the core mechanism behind the First-Level Cache (Session cache) in Hibernate and the JPA EntityManager.

Recommended Design Pattern Tutorials:


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

Click the below Image to Enlarge
Identity Map Design Pattern














See also:

  • All Design Patterns Links
  • Saturday, 24 August 2013

    Object-Relational Structural Patterns

    🚀 Master Enterprise Architecture & Design Patterns!

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

    🔔 Subscribe Now

    What are Object-Relational Structural Patterns?

    When building enterprise applications, developers often face an object-relational impedance mismatch—the challenge of bridging object-oriented programming models (classes, objects, inheritance, relationships) with relational databases (tables, rows, foreign keys).

    In Martin Fowler’s Patterns of Enterprise Application Architecture (PofEAA), Object-Relational Structural Patterns provide proven architectural strategies to map in-memory domain objects to relational table structures smoothly and efficiently.

    Complete List of Structural Patterns

    These patterns cover relationships, complex value mappings, and class hierarchies:

    • Identity Field: Saves a database ID field in an object to maintain identity between an in-memory object and an equivalent database row.
    • Foreign Key Mapping: Maps an association between objects to a foreign key reference between relational tables.
    • Association Table Mapping: Maps many-to-many associations between classes using an intermediate link table.
    • Dependent Mapping: Manages child objects directly through a parent object, simplifying child persistence.
    • Embedded Value: Maps an object into multiple fields of another object's database table.
    • Serialized LOB (Large Object): Serializes a complex object graph into a single database column (such as BLOB, CLOB, or JSON).
    • Single Table Inheritance: Represents an entire class inheritance hierarchy as a single table with columns for all attributes.
    • Class Table Inheritance: Represents each class in an inheritance hierarchy with its own individual table.
    • Concrete Table Inheritance: Represents each concrete class in an inheritance hierarchy with a separate database table.
    • Inheritance Mappers: Coordinates database mappers to handle an inheritance hierarchy properly.

    Why Are These Patterns Important?

    • Maintainable Data Access: Eliminates ad-hoc, brittle database queries by establishing structured mapping rules.
    • Foundation of ORM Tools: Understanding these concepts reveals how modern ORM frameworks like Hibernate and JPA work behind the scenes.
    • Flexible Schema Evolution: Enables developers to alter relational schemas or domain models with minimal friction.

    Recommended Design Pattern Tutorials:


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

    Click the below Image to Enlarge
    Object-Relational Structural  Patterns














    See also:

  • All Design Patterns Links
  • Object-Relational Behavioral Patterns

    🚀 Master Enterprise Java & Software Architecture!

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

    🔔 Subscribe Now

    What are Object-Relational Behavioral Patterns?

    In enterprise software development, mapping in-memory domain objects to a relational database is not just about table structure—it is equally about runtime behavior and state synchronization.

    In Martin Fowler’s Patterns of Enterprise Application Architecture (PofEAA), Object-Relational Behavioral Patterns define how objects interact with the database during active business transactions. They coordinate how and when objects load data, track modifications, and commit changes cleanly to the database.

    The 3 Core Object-Relational Behavioral Patterns

    There are three fundamental architectural patterns that govern object-relational behavior:

    1. Unit of Work Pattern

    Maintains a list of business objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. Instead of hitting the database on every modification, the Unit of Work tracks all new, dirty, and deleted objects, flushing them to the database in a single optimized transaction.

    2. Identity Map Pattern

    Ensures that each object gets loaded only once by keeping every loaded object in a map. When you request an object, the Identity Map checks whether it is already loaded in memory before issuing an SQL query to the database, preventing duplicate in-memory instances representing the same database row.

    3. Lazy Load Pattern

    Defers the loading of an object or relationship until the point at which it is actually needed. This keeps database queries fast and minimizes memory consumption by avoiding the retrieval of entire object graphs upfront.

    Why Do These Patterns Matter in Modern Systems?

    • Optimized Performance: Eliminates duplicate database queries and groups updates into batch operations.
    • Data Consistency: Prevents conflicting in-memory states by ensuring one canonical object exists per database entity.
    • Underpins ORM Frameworks: Forms the exact operational engine behind the Hibernate/JPA EntityManager and Spring transaction management.

    Recommended Design Pattern Tutorials:


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

    Click the below Image to Enlarge
    Object-Relational Behavioral Patterns














    See also:

  • All Design Patterns Links
  • Monday, 12 August 2013

    Metadata Mapping Design Pattern

    🚀 Master Enterprise Java & Software Architecture!

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

    🔔 Subscribe Now

    What is the Metadata Mapping Design Pattern?

    The Metadata Mapping Pattern is one of the key Object-Relational Metadata Mapping Patterns from Martin Fowler's classic architectural book, Patterns of Enterprise Application Architecture (PofEAA).

    Core Definition: The pattern holds details of object-relational mapping in metadata.

    What is Metadata? Metadata is simply "data about data"—it provides descriptive information about a particular item. For example, image metadata describes its dimensions, resolution, color depth, author, and creation timestamp. In database architecture, metadata describes how domain classes, fields, tables, and columns relate to each other.

    Real-World Example: Person Table and Person Class

    Imagine a database table named person with three columns:

    • last_name (stores surname, e.g., "Joe", "Goni")
    • first_name (stores given name)
    • number_of_dependents (stores count of family dependents)

    In your application, you have an equivalent Java domain class:

    public class Person {
        private String lastName;
        private String firstName;
        private int numberOfDependents;
    
        // Getters and Setters
    }

    How Metadata Bridges Objects and Relational Tables

    Instead of hardcoding SQL statements inside the Person class or writing repetitive data access methods by hand, we define a Person Metadata configuration (typically in an XML file, JSON, or annotations):

    • Class to Table: Person class → maps to person table.
    • Field to Column: lastName → maps to last_name.
    • Field to Column: firstName → maps to first_name.
    • Field to Column: numberOfDependents → maps to number_of_dependents.

    How Generic Code Uses the Metadata (Hibernate / ORM Example)

    The true power of this pattern emerges when generic framework code processes this metadata:

    1. A generic data access engine (like Hibernate ORM) reads the mapping metadata during startup.
    2. When you tell Hibernate to save or query an object, its generic engine inspects the metadata to construct dynamic SQL queries (INSERT, UPDATE, SELECT, DELETE).
    3. It reads values from entity properties and writes them into the correct table columns automatically.

    Key Advantages of Metadata Mapping

    • Drastically Reduces Boilerplate: Eliminates repetitive, hand-crafted SQL strings and manual result-set parsing across your codebase.
    • Centralized Mapping Definitions: If table columns or class properties change, you only update the metadata mapping definition without rewriting database logic.
    • Foundation of Modern Frameworks: Forms the exact architectural backbone of JPA annotations (@Table, @Column) and Hibernate XML mapping files (.hbm.xml).

    Recommended Design Pattern Tutorials:


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

    Click the below Image to Enlarge
    Metadata Mapping Design Pattern















    See also:

  • All Design Patterns Links
  • Saturday, 10 August 2013

    Serialized LOB 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 Serialized LOB Design Pattern?

    The Serialized LOB Pattern is an important Object-Relational Structural Pattern from Martin Fowler's classic enterprise book, Patterns of Enterprise Application Architecture (PofEAA).

    Core Definition: The pattern saves a graph of objects by serializing them into a single Large Object (LOB) which it stores directly in a database field.

    A LOB can be a BLOB (Binary Large Object), a CLOB (Character Large Object), or structured text formats like JSON or XML.

    The Problem: Storing Complex Hierarchies in Relational Tables

    Consider an organizational tree structure:

    • CEO (John): Oversees two department heads: Rob and Peter.
    • Rob: Manages two sales executives: Julie and Mark.
    • Peter: Manages two clerks: David and Steve.

    Mapping this deep hierarchical tree into a standard relational database requires parent-child tables with recursive foreign keys. Querying and updating deep object graphs requires multiple nested SQL JOIN operations, which degrades performance and creates complex database manipulation logic.

    The Solution: Serialize the Object Graph into a LOB

    Instead of decomposing an object graph across several relational tables, you serialize the entire in-memory object hierarchy into a single formatted payload (such as JSON, XML, or binary data) and store it in one database column:

    CREATE TABLE organization_unit (
        unit_id BIGINT PRIMARY KEY,
        unit_name VARCHAR(100),
        department_graph CLOB  -- Serialized LOB column storing the complete tree
    );

    When reading the data, your application retrieves that single field and deserializes it back into an active, connected graph of objects in memory with a single read operation.

    Advantages & Trade-offs

    • Zero Recursive JOINs: Fetching complex object graphs requires only a single database query row.
    • Simplified Persistence: Adding new fields or nodes to the graph does not require altering the database schema.
    • Query Limitations: You generally cannot query individual fields inside a serialized LOB using standard relational SQL (unless using native JSON functions).
    • Best Used For: Object graphs that are always retrieved, modified, and saved together as a single cohesive unit.

    Recommended Design Pattern Tutorials:


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

    Click the below Image to Enlarge
    Serialized LOB Design Pattern















    See also:

  • All Design Patterns Links
  • Friday, 9 August 2013

    Embedded Value 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 Embedded Value Design Pattern?

    The Embedded Value Pattern is a foundational Object-Relational Structural Pattern described in Martin Fowler’s Patterns of Enterprise Application Architecture (PofEAA).

    Core Definition: The Embedded Value pattern maps an object into several fields of another object's database table.

    In object-oriented design, it is common to create small, cohesive value objects (such as an Address or Money object) to structure business concepts cleanly. However, creating a separate database table for every tiny object adds unnecessary schema complexity and hurts query performance. Embedded Value solves this problem cleanly.

    Real-World Example: Shipping Item & Address

    Consider an e-commerce shipping scenario with two classes: ShippingItem and Address.

    • ShippingItem has fields: shippingId, itemName, shippingDate, and an Address destination.
    • Address has fields: street, city, state, and postalCode.

    Because a shipping item is delivered to a single delivery destination, this is a strict 1-to-1 relationship.

    The Problem: Multiple Tables & Costly JOINs

    If you create two distinct database tables—a shipping_items table and an addresses table—retrieving complete item details requires an SQL INNER JOIN:

    SELECT s.*, a.* 
    FROM shipping_items s 
    INNER JOIN addresses a ON s.shipping_id = a.shipping_id;

    Executing database joins for small dependent objects increases query overhead, consumes memory, and slows down application response times.

    The Solution: Flattening Fields with Embedded Value

    Instead of two tables, we merge the fields of the dependent Address object directly into the shipping_items table as additional columns:

    • shipping_id (Primary Key)
    • item_name
    • shipping_date
    • street, city, state, postal_code (Embedded Address Columns)

    Now, fetching complete data requires only a fast, single-table query:

    SELECT * FROM shipping_items WHERE shipping_id = 1;

    Key Advantages of Embedded Value

    • Zero SQL JOINs: Greatly accelerates database reads and updates by keeping data co-located in a single row.
    • Preserves Clean OOP Models: Your Java code continues using clean, encapsulated domain objects (e.g., item.getDestination().getCity()) without polluting business rules.
    • Standard in ORM Frameworks: Forms the core mechanism behind JPA's @Embeddable and @Embedded annotations in Hibernate.

    Recommended Design Pattern Tutorials:


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

    Click the below Image to Enlarge
    Embedded Value Design Pattern














    See also:

  • All Design Patterns Links
  • Dependent 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 Dependent Mapping Design Pattern?

    The Dependent Mapping Pattern is one of the essential Object-Relational Structural Patterns defined in Martin Fowler’s Patterns of Enterprise Application Architecture (PofEAA).

    Core Definition: In the Dependent Mapping pattern, the parent class performs all database mapping operations on behalf of a child (dependent) class.

    This pattern serves as a practical, lightweight alternative to standard Foreign Key Mapping when an object cannot exist independently of its parent object.

    Key Principles of Dependent Mapping

    • Parent Controls Persistence: The dependent class does not have its own independent database mapper or repository. Instead, the parent entity orchestrates loading, updating, and saving child records.
    • No Independent Identity: The dependent object is strictly scoped to its parent lifecycle—if the parent is deleted or queried, the child follows automatically.
    • Simpler Domain Models: In simple domain architectures, placing database mapping logic directly in the parent simplifies the overall system and reduces unnecessary boilerplate classes.

    Real-World Example: Person and Address

    Consider two database tables: a Person table and an Address table.

    • Person Table: Columns are person_id (Primary Key), name, age, and gender.
    • Address Table: Columns are address_id (Primary Key), person_id (Foreign Key), and city.

    A person named Joe may have three addresses (Bangalore, Chennai, Delhi), and Goni may have two addresses (Mumbai, Kerala). Rather than managing addresses through an independent address service, the Person class handles the mapping:

    public class Person {
        private Long personId;
        private String name;
        private int age;
        private String gender;
        private Set<Address> addresses = new HashSet<>();
    
        // Loads dependent address data from the address table
        public void loadAddress() {
            // Query Address table where person_id = this.personId
            // Populate the addresses collection
        }
    
        // Saves dependent address records alongside person data
        public void saveAddress() {
            // Persist all addresses referencing this.personId
        }
    }

    When Should You Use Dependent Mapping?

    • When child objects are tightly coupled to a single parent and are never referenced by other entities.
    • When you want to treat child objects as direct value objects or dependent components without building separate data access infrastructure.
    • When you want to simplify transaction and cascade management directly within the parent domain boundary.

    Recommended Design Pattern Tutorials:


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

    Click the below Image to Enlarge
    Dependent Mapping Design Pattern















    See also:

  • All Design Patterns Links
  • Association Table Mapping Design Pattern

    🚀 Master Enterprise Java & Architecture Patterns!

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

    🔔 Subscribe Now

    What is the Association Table Mapping Design Pattern?

    The Association Table Mapping Pattern is an essential Object-Relational Structural Pattern documented in Martin Fowler's classic guide, Patterns of Enterprise Application Architecture (PofEAA).

    The Core Definition: It saves an association between two tables as a separate link table that contains foreign keys referencing each of the linked tables. This pattern is the standard architectural mechanism used to map Many-to-Many relationships between relational database tables and object-oriented domain models.

    Real-World Example: Persons and Addresses (Many-to-Many)

    Consider a scenario where multiple people can share multiple addresses:

    • Joe lives in both Bangalore and Chennai.
    • Goni lives in Bangalore, Chennai, and Kerala.
    • Notice that the city of Bangalore belongs to both Joe and Goni. This is a true Many-to-Many relationship.

    Database Schema Structure: The 3 Tables

    In a relational database, you cannot store multiple foreign keys in a single column without violating normalization rules. To solve this, we create three distinct tables:

    1. Person Table: Stores individual personal records (person_id, name, age).
    2. Address Table: Stores unique address locations (address_id, city).
    3. Person_Address Link Table (Association Table): Contains foreign keys pointing to both entities (person_id, address_id). Each row represents a single connection between a person and an address.

    Mapping to In-Memory Java Classes

    In object-oriented code, this link table is translated seamlessly into collections of references:

    // Person entity containing a collection of Addresses
    public class Person {
        private Long personId;
        private String name;
        private int age;
        private Set<Address> addresses = new HashSet<>();
    
        // Getters and Setters
    }
    
    // Address entity containing a collection of Persons
    public class Address {
        private Long addressId;
        private String city;
        private Set<Person> persons = new HashSet<>();
    
        // Getters and Setters
    }

    When you load Joe, the data mapper reads the intermediate link table and populates Joe's addresses set with Bangalore and Chennai. Conversely, when you inspect Bangalore, its persons set contains both Joe and Goni.

    Key Benefits of Association Table Mapping

    • Normalized Relational Schema: Keeps base tables cleanly decoupled without storing denormalized arrays or delimited strings in columns.
    • Bidirectional Traversal: Enables smooth navigation from either side of the relationship (Person to Address or Address to Person).
    • JPA/Hibernate Standard: Forms the exact architectural foundation used by the @ManyToMany and @JoinTable annotations in modern ORM frameworks.

    Recommended Design Pattern Tutorials:


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

    Click the below Image to Enlarge
    Association Table Mapping Design Pattern















    See also:

  • All Design Patterns Links
  • 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
  • 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:
    Older Posts Home

    Tutorials