Showing posts with label Embedded Value. Show all posts
Showing posts with label Embedded Value. Show all posts

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
  • Tutorials