Programming Search⌘K

Patterncore

Embedded Value

Also called embedded value pattern, composite column mapping, embeddable, complex type mapping.

An Embedded Value saves a small value object, such as an amount of money or a date range, in columns of its owner's table instead of in a table of its own.

Family
architectural
Intent
Maps an object into several fields of another object's table.

Intent

An Embedded Value "Maps an object into several fields of another object's table."1 The value has no row and no key of its own. Its fields are columns in the row of the object that holds it.

Problem

A good object model has many small objects. Fowler writes: "Many small objects make sense in an OO system that don't make sense as tables in a database. Examples include currency-aware money objects and date ranges."1 These are value objects: "two value objects are equal when they have the same value , not necessarily being the same object ."2 The default way to map a class is to give it a table, "no sane person would want a table of money values."1 A table for each value adds a key that means nothing, a join for each load, and a row that two owners can share by mistake.

Solution

"An Embedded Value maps the values of an object to fields in the record of the object's owner."1 When the mapper saves the owner, it writes the fields of each value object to columns of the owner's row. When it loads the owner, it reads these columns and builds a new value object from them.

  memory                                         database: employment
  Employment                                     id | person | start_date | end_date   | salary_amount | salary_currency
    person = "Ann"                               1  | Ann    | 2024-01-01 | 2024-12-31 | 5000          | EUR
    period = DateRange(2024-01-01, 2024-12-31)  -> start_date, end_date
    salary = Money(5000, EUR)                    -> salary_amount, salary_currency

The participants are the owner, an object with an identity and a row of its own; the value object, which has no identity and is compared by its fields; and the owner's mapper, which writes the value into a group of columns and builds it again on load. The value object does not need a mapper of its own.

The following program saves an employment with a date range and a salary in one row, and loads it again.

import sqlite3
from dataclasses import dataclass

db = sqlite3.connect(":memory:")
db.execute("""create table employment (id integer primary key, person text,
              start_date text, end_date text, salary_amount integer, salary_currency text)""")


@dataclass(frozen=True)
class DateRange:  # A value object: no key, compared by its fields.
    start: str
    end: str


@dataclass(frozen=True)
class Money:
    amount: int
    currency: str


class Employment:
    def __init__(self, person, period, salary, id=None):
        self.id, self.person, self.period, self.salary = id, person, period, salary


def insert(e):
    # Each value object goes into columns of the owner's row, not into a table of its own.
    sql = "insert into employment values (null, ?, ?, ?, ?, ?)"
    p, s = e.period, e.salary
    e.id = db.execute(sql, (e.person, p.start, p.end, s.amount, s.currency)).lastrowid


def find(id):
    sql = "select * from employment where id = ?"
    id, person, start, end, amount, currency = db.execute(sql, (id,)).fetchone()
    return Employment(person, DateRange(start, end), Money(amount, currency), id)


insert(Employment("Ann", DateRange("2024-01-01", "2024-12-31"), Money(5000, "EUR")))
print(db.execute("select * from employment").fetchall())
ann = find(1)
print(ann.person, "|", ann.period, "|", ann.salary)
print("equal by value:", ann.salary == Money(5000, "EUR"))
Output
[(1, 'Ann', '2024-01-01', '2024-12-31', 5000, 'EUR')]
Ann | DateRange(start='2024-01-01', end='2024-12-31') | Money(amount=5000, currency='EUR')
equal by value: True

The loaded Money is a new object, but it is equal to Money(5000, "EUR") because a value object is compared by its fields.

Example

Each example file saves two employments, one with an end date and one without, and prints the flat rows. A missing end date is a null column. It loads both and builds new DateRange and Money values from the columns. Ann gets a raise: the program puts a new Money value into the employment of Ann and saves it, and the salary of Bo does not change. The last query finds the salaries above 4500 EUR with the columns of the value, which the database can read and index as other columns. The Python file uses SQLite. The JavaScript, Java, Go and Rust files keep the table in memory as flat rows of columns.

PythonGitHub
import sqlite3
from dataclasses import dataclass

db = sqlite3.connect(":memory:")
db.execute("""create table employment (id integer primary key, person text,
              start_date text, end_date text, salary_amount integer, salary_currency text)""")


@dataclass(frozen=True)
class DateRange:
    start: str
    end: str | None  # None: the employment has not ended.

    def __str__(self):
        return f"{self.start} to {self.end or 'open'}"


@dataclass(frozen=True)
class Money:
    amount: int
    currency: str

    def __str__(self):
        return f"{self.amount} {self.currency}"


class Employment:
    def __init__(self, person, period, salary, id=None):
        self.id, self.person, self.period, self.salary = id, person, period, salary


def insert(e):
    sql = "insert into employment values (null, ?, ?, ?, ?, ?)"
    p, s = e.period, e.salary
    e.id = db.execute(sql, (e.person, p.start, p.end, s.amount, s.currency)).lastrowid


def update(e):
    sql = """update employment set person = ?, start_date = ?, end_date = ?,
             salary_amount = ?, salary_currency = ? where id = ?"""
    p, s = e.period, e.salary
    db.execute(sql, (e.person, p.start, p.end, s.amount, s.currency, e.id))


def find(id):
    sql = "select * from employment where id = ?"
    id, person, start, end, amount, currency = db.execute(sql, (id,)).fetchone()
    return Employment(person, DateRange(start, end), Money(amount, currency), id)


def show_rows():
    for row in db.execute("select * from employment order by id"):
        print("row:", " ".join("null" if v is None else str(v) for v in row))


insert(Employment("Ann", DateRange("2024-01-01", "2024-12-31"), Money(5000, "EUR")))
insert(Employment("Bo", DateRange("2025-03-01", None), Money(4000, "EUR")))
show_rows()
ann, bo = find(1), find(2)
for e in (ann, bo):
    print(f"loaded: {e.person} | {e.period} | {e.salary}")
same = "yes" if ann.salary == Money(5000, "EUR") else "no"
print(f"salary of Ann equals 5000 EUR: {same}")

ann.salary = Money(5500, "EUR")  # A new value replaces the old one.
update(ann)
print(f"after raise: Ann {find(1).salary} | Bo {find(2).salary}")

sql = "select person from employment where salary_currency = 'EUR' and salary_amount > 4500"
print("EUR salaries above 4500:", ", ".join(p for (p,) in db.execute(sql)))
Output
row: 1 Ann 2024-01-01 2024-12-31 5000 EUR
row: 2 Bo 2025-03-01 null 4000 EUR
loaded: Ann | 2024-01-01 to 2024-12-31 | 5000 EUR
loaded: Bo | 2025-03-01 to open | 4000 EUR
salary of Ann equals 5000 EUR: yes
after raise: Ann 5500 EUR | Bo 4000 EUR
EUR salaries above 4500: Ann
  • Verdict: idiom. DateRange and Money are frozen dataclasses, so they compare by their fields and cannot change after they are made. A raise is a new Money value.
  • insert and update write the fields of both values to the columns of the employment row, and find builds new values from these columns. A null end_date becomes None.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    // Value objects: records are immutable and compare by their fields.
    record DateRange(String start, String end) {
        @Override
        public String toString() {
            return start + " to " + (end == null ? "open" : end);
        }
    }

    record Money(int amount, String currency) {
        @Override
        public String toString() {
            return amount + " " + currency;
        }
    }

    // The row: the columns of the employment table.
    record Row(String person, String startDate, String endDate, int salaryAmount, String salaryCurrency) {}

    // A stand-in for the database: one table keyed by id.
    static final Map<Long, Row> EMPLOYMENT = new TreeMap<>();
    static long lastId = 0;

    static class Employment {
        Long id;
        String person;
        DateRange period;
        Money salary;

        Employment(String person, DateRange period, Money salary, Long id) {
            this.person = person;
            this.period = period;
            this.salary = salary;
            this.id = id;
        }
    }

    static Row toRow(Employment e) {
        return new Row(e.person, e.period.start(), e.period.end(), e.salary.amount(), e.salary.currency());
    }

    static void insert(Employment e) {
        EMPLOYMENT.put(++lastId, toRow(e));
        e.id = lastId;
    }

    static void update(Employment e) {
        EMPLOYMENT.put(e.id, toRow(e));
    }

    static Employment find(long id) {
        Row r = EMPLOYMENT.get(id);
        return new Employment(r.person(), new DateRange(r.startDate(), r.endDate()),
                new Money(r.salaryAmount(), r.salaryCurrency()), id);
    }

    static String show(Object v) {
        return v == null ? "null" : v.toString();
    }

    public static void main(String[] args) {
        insert(new Employment("Ann", new DateRange("2024-01-01", "2024-12-31"), new Money(5000, "EUR"), null));
        insert(new Employment("Bo", new DateRange("2025-03-01", null), new Money(4000, "EUR"), null));
        EMPLOYMENT.forEach((id, r) -> System.out.println("row: " + id + " " + r.person() + " " + r.startDate() + " "
                + show(r.endDate()) + " " + r.salaryAmount() + " " + r.salaryCurrency()));
        Employment ann = find(1);
        Employment bo = find(2);
        for (Employment e : List.of(ann, bo)) {
            System.out.println("loaded: " + e.person + " | " + e.period + " | " + e.salary);
        }
        String same = ann.salary.equals(new Money(5000, "EUR")) ? "yes" : "no";
        System.out.println("salary of Ann equals 5000 EUR: " + same);

        ann.salary = new Money(5500, "EUR"); // A new value replaces the old one.
        update(ann);
        System.out.println("after raise: Ann " + find(1).salary + " | Bo " + find(2).salary);

        List<String> above = new ArrayList<>();
        for (Row r : EMPLOYMENT.values()) {
            if (r.salaryCurrency().equals("EUR") && r.salaryAmount() > 4500) {
                above.add(r.person());
            }
        }
        System.out.println("EUR salaries above 4500: " + String.join(", ", above));
    }
}
Output
row: 1 Ann 2024-01-01 2024-12-31 5000 EUR
row: 2 Bo 2025-03-01 null 4000 EUR
loaded: Ann | 2024-01-01 to 2024-12-31 | 5000 EUR
loaded: Bo | 2025-03-01 to open | 4000 EUR
salary of Ann equals 5000 EUR: yes
after raise: Ann 5500 EUR | Bo 4000 EUR
EUR salaries above 4500: Ann
  • Verdict: idiom. DateRange and Money are records, which are immutable and get equals and hashCode from their components.
  • With JPA or Hibernate, an @Embeddable class and an @Embedded field give the same mapping, and @AttributeOverride renames the columns when two values have the same type.
JavaScriptGitHub
// A stand-in for the database: one table whose rows are flat lists of columns.
// Columns: person, start_date, end_date, salary_amount, salary_currency.
const employmentTable = new Map();
let lastId = 0;

class DateRange {
  constructor(start, end) {
    this.start = start;
    this.end = end; // null: the employment has not ended.
    Object.freeze(this);
  }
  toString() {
    return `${this.start} to ${this.end ?? "open"}`;
  }
}

class Money {
  constructor(amount, currency) {
    this.amount = amount;
    this.currency = currency;
    Object.freeze(this);
  }
  equals(other) {
    return this.amount === other.amount && this.currency === other.currency;
  }
  toString() {
    return `${this.amount} ${this.currency}`;
  }
}

class Employment {
  constructor(person, period, salary, id = null) {
    this.id = id;
    this.person = person;
    this.period = period;
    this.salary = salary;
  }
}

function toRow(e) {
  return [e.person, e.period.start, e.period.end, e.salary.amount, e.salary.currency];
}

function insert(e) {
  lastId += 1;
  employmentTable.set(lastId, toRow(e));
  e.id = lastId;
}

function update(e) {
  employmentTable.set(e.id, toRow(e));
}

function find(id) {
  const [person, start, end, amount, currency] = employmentTable.get(id);
  return new Employment(person, new DateRange(start, end), new Money(amount, currency), id);
}

function showRows() {
  for (const [id, row] of employmentTable) {
    console.log(`row: ${[id, ...row].map((v) => (v === null ? "null" : String(v))).join(" ")}`);
  }
}

insert(new Employment("Ann", new DateRange("2024-01-01", "2024-12-31"), new Money(5000, "EUR")));
insert(new Employment("Bo", new DateRange("2025-03-01", null), new Money(4000, "EUR")));
showRows();
const ann = find(1);
const bo = find(2);
for (const e of [ann, bo]) console.log(`loaded: ${e.person} | ${e.period} | ${e.salary}`);
const same = ann.salary.equals(new Money(5000, "EUR")) ? "yes" : "no";
console.log(`salary of Ann equals 5000 EUR: ${same}`);

ann.salary = new Money(5500, "EUR"); // A new value replaces the old one.
update(ann);
console.log(`after raise: Ann ${find(1).salary} | Bo ${find(2).salary}`);

const above = [...employmentTable.values()]
  .filter(([, , , amount, currency]) => currency === "EUR" && amount > 4500)
  .map(([person]) => person);
console.log(`EUR salaries above 4500: ${above.join(", ")}`);
Output
row: 1 Ann 2024-01-01 2024-12-31 5000 EUR
row: 2 Bo 2025-03-01 null 4000 EUR
loaded: Ann | 2024-01-01 to 2024-12-31 | 5000 EUR
loaded: Bo | 2025-03-01 to open | 4000 EUR
salary of Ann equals 5000 EUR: yes
after raise: Ann 5500 EUR | Bo 4000 EUR
EUR salaries above 4500: Ann
  • Verdict: idiom. The value classes call Object.freeze(this) in the constructor, so their fields cannot change. JavaScript compares objects by reference, so Money has an equals method that compares the fields.
  • toRow flattens an employment into a list of columns, and find builds new DateRange and Money objects from the list.
package main

import (
	"fmt"
	"sort"
	"strings"
)

// Value objects: structs without a key, compared with == by their fields.
type DateRange struct {
	Start string
	End   *string // nil: the employment has not ended.
}

func (d DateRange) String() string {
	end := "open"
	if d.End != nil {
		end = *d.End
	}
	return d.Start + " to " + end
}

type Money struct {
	Amount   int
	Currency string
}

func (m Money) String() string { return fmt.Sprintf("%d %s", m.Amount, m.Currency) }

// The row: the columns of the employment table.
type row struct {
	person, startDate string
	endDate           *string
	salaryAmount      int
	salaryCurrency    string
}

// A stand-in for the database: one table keyed by id.
var employmentTable = map[int64]row{}
var lastID int64

type Employment struct {
	ID     int64
	Person string
	Period DateRange
	Salary Money
}

func toRow(e *Employment) row {
	return row{e.Person, e.Period.Start, e.Period.End, e.Salary.Amount, e.Salary.Currency}
}

func insert(e *Employment) {
	lastID++
	employmentTable[lastID] = toRow(e)
	e.ID = lastID
}

func update(e *Employment) { employmentTable[e.ID] = toRow(e) }

func find(id int64) *Employment {
	r := employmentTable[id]
	return &Employment{id, r.person, DateRange{r.startDate, r.endDate}, Money{r.salaryAmount, r.salaryCurrency}}
}

func ids() []int64 {
	keys := make([]int64, 0, len(employmentTable))
	for k := range employmentTable {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
	return keys
}

func main() {
	end := "2024-12-31"
	insert(&Employment{Person: "Ann", Period: DateRange{"2024-01-01", &end}, Salary: Money{5000, "EUR"}})
	insert(&Employment{Person: "Bo", Period: DateRange{"2025-03-01", nil}, Salary: Money{4000, "EUR"}})
	for _, id := range ids() {
		r := employmentTable[id]
		endDate := "null"
		if r.endDate != nil {
			endDate = *r.endDate
		}
		fmt.Printf("row: %d %s %s %s %d %s\n", id, r.person, r.startDate, endDate, r.salaryAmount, r.salaryCurrency)
	}
	ann, bo := find(1), find(2)
	for _, e := range []*Employment{ann, bo} {
		fmt.Printf("loaded: %s | %s | %s\n", e.Person, e.Period, e.Salary)
	}
	same := "no"
	if ann.Salary == (Money{5000, "EUR"}) {
		same = "yes"
	}
	fmt.Println("salary of Ann equals 5000 EUR:", same)

	ann.Salary = Money{5500, "EUR"} // A new value replaces the old one.
	update(ann)
	fmt.Printf("after raise: Ann %s | Bo %s\n", find(1).Salary, find(2).Salary)

	var above []string
	for _, id := range ids() {
		if r := employmentTable[id]; r.salaryCurrency == "EUR" && r.salaryAmount > 4500 {
			above = append(above, r.person)
		}
	}
	fmt.Println("EUR salaries above 4500:", strings.Join(above, ", "))
}
Output
row: 1 Ann 2024-01-01 2024-12-31 5000 EUR
row: 2 Bo 2025-03-01 null 4000 EUR
loaded: Ann | 2024-01-01 to 2024-12-31 | 5000 EUR
loaded: Bo | 2025-03-01 to open | 4000 EUR
salary of Ann equals 5000 EUR: yes
after raise: Ann 5500 EUR | Bo 4000 EUR
EUR salaries above 4500: Ann
  • Verdict: idiom. The values are structs that the program passes by value, and == compares Money values field by field. The end date is a *string, so nil stands for a null column; == on a DateRange would compare this pointer and not the text.
  • toRow copies the fields of the values into a flat row struct, and find builds new values from it.
RustGitHub
use std::collections::BTreeMap;
use std::fmt;

// Value objects: no key, compared by their fields with the derived PartialEq.
#[derive(Clone, Debug, PartialEq)]
struct DateRange {
    start: String,
    end: Option<String>, // None: the employment has not ended.
}

impl fmt::Display for DateRange {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} to {}", self.start, self.end.as_deref().unwrap_or("open"))
    }
}

#[derive(Clone, Debug, PartialEq)]
struct Money {
    amount: i64,
    currency: String,
}

impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", self.amount, self.currency)
    }
}

fn money(amount: i64, currency: &str) -> Money {
    Money { amount, currency: currency.to_string() }
}

// The row: the columns of the employment table.
struct Row {
    person: String,
    start_date: String,
    end_date: Option<String>,
    salary_amount: i64,
    salary_currency: String,
}

struct Employment {
    id: Option<i64>,
    person: String,
    period: DateRange,
    salary: Money,
}

// A stand-in for the database: one table keyed by id.
#[derive(Default)]
struct Db {
    employment: BTreeMap<i64, Row>,
    last_id: i64,
}

impl Db {
    fn to_row(e: &Employment) -> Row {
        Row {
            person: e.person.clone(),
            start_date: e.period.start.clone(),
            end_date: e.period.end.clone(),
            salary_amount: e.salary.amount,
            salary_currency: e.salary.currency.clone(),
        }
    }

    fn insert(&mut self, e: &mut Employment) {
        self.last_id += 1;
        self.employment.insert(self.last_id, Db::to_row(e));
        e.id = Some(self.last_id);
    }

    fn update(&mut self, e: &Employment) {
        if let Some(id) = e.id {
            self.employment.insert(id, Db::to_row(e));
        }
    }

    fn find(&self, id: i64) -> Employment {
        let r = &self.employment[&id];
        Employment {
            id: Some(id),
            person: r.person.clone(),
            period: DateRange { start: r.start_date.clone(), end: r.end_date.clone() },
            salary: money(r.salary_amount, &r.salary_currency),
        }
    }
}

fn main() {
    let mut db = Db::default();
    let mut ann = Employment {
        id: None,
        person: "Ann".to_string(),
        period: DateRange { start: "2024-01-01".to_string(), end: Some("2024-12-31".to_string()) },
        salary: money(5000, "EUR"),
    };
    let mut bo = Employment {
        id: None,
        person: "Bo".to_string(),
        period: DateRange { start: "2025-03-01".to_string(), end: None },
        salary: money(4000, "EUR"),
    };
    db.insert(&mut ann);
    db.insert(&mut bo);
    for (id, r) in &db.employment {
        let end = r.end_date.as_deref().unwrap_or("null");
        println!("row: {} {} {} {} {} {}", id, r.person, r.start_date, end, r.salary_amount, r.salary_currency);
    }
    let mut ann = db.find(1);
    let bo = db.find(2);
    for e in [&ann, &bo] {
        println!("loaded: {} | {} | {}", e.person, e.period, e.salary);
    }
    let same = if ann.salary == money(5000, "EUR") { "yes" } else { "no" };
    println!("salary of Ann equals 5000 EUR: {}", same);

    ann.salary = money(5500, "EUR"); // A new value replaces the old one.
    db.update(&ann);
    println!("after raise: Ann {} | Bo {}", db.find(1).salary, db.find(2).salary);

    let above: Vec<&str> = db
        .employment
        .values()
        .filter(|r| r.salary_currency == "EUR" && r.salary_amount > 4500)
        .map(|r| r.person.as_str())
        .collect();
    println!("EUR salaries above 4500: {}", above.join(", "));
}
Output
row: 1 Ann 2024-01-01 2024-12-31 5000 EUR
row: 2 Bo 2025-03-01 null 4000 EUR
loaded: Ann | 2024-01-01 to 2024-12-31 | 5000 EUR
loaded: Bo | 2025-03-01 to open | 4000 EUR
salary of Ann equals 5000 EUR: yes
after raise: Ann 5500 EUR | Bo 4000 EUR
EUR salaries above 4500: Ann
  • Verdict: idiom. DateRange and Money derive PartialEq, so == compares their fields. The end date is an Option<String>, so None stands for a null column.
  • to_row copies the values into a flat Row, and find clones the columns into new values. The owner holds its values, so no other owner can change them.

Consequences

Benefits.

  • One row, one read. The owner and its values load with one query and save with one statement, without joins.
  • The database can query the parts. Each field of the value is a column, so a query can filter, sort and index on the amount or the currency.
  • No key that means nothing. The value object has no identity, so the table needs no key for it and no Identity Field in the class.
  • The object model keeps its small types. Code works with Money and DateRange, which can hold the rules of the value, and not with loose columns.

Liabilities.

A value that is shared changes for all its owners. Fowler's book names value objects as the clear case for the pattern.3 A program that gives a value a table and a key can make two owners point to the same row. In the following program, Ann and Bo share one money row, and a raise for Ann also changes the salary of Bo.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table money (id integer primary key, amount integer, currency text);
create table employment (id integer primary key, person text, salary_id integer references money(id));
insert into money values (1, 5000, 'EUR');
-- Bo has the same salary as Ann, so the mapper reuses the row of that value.
insert into employment values (1, 'Ann', 1), (2, 'Bo', 1);
""")

# Ann gets a raise. The program changes the money row of Ann.
db.execute("update money set amount = 5500 where id = (select salary_id from employment where person = 'Ann')")
sql = "select e.person, m.amount from employment e join money m on m.id = e.salary_id order by e.id"
print(db.execute(sql).fetchall())
Output
[('Ann', 5500), ('Bo', 5500)]

The fix is to keep the salary in the columns of each employment, and to make the value objects immutable, so that a change is a new value and not a write to a shared object. "Value objects should be immutable".2 Entity Framework Core gives the same advice for its complex types: "Because a reference-type instance can be shared by multiple properties, mutating one of its properties changes the value everywhere it is used."4

Wide tables and column names. Each value adds columns, and two values of the same type, such as a home address and a work address, need a prefix for each group of columns.

Null is not a value. If all the columns of a value are null, the mapper must decide whether the value is missing or is a value with null fields. SQLAlchemy builds the composite on access only when the object is already in the database or when one of its columns is not null, and it sets all the columns to None when the attribute is set to None.5

When not to use it

When the object has an identity. If other objects refer to it, or if it changes over time and must stay the same object, it is an entity. Give it a table and a key, and use a Foreign Key Mapping.

For a collection of values. A list of values does not fit in a fixed group of columns. Use a table that the owner's mapper writes, as in Dependent Mapping, or a serialized column. Entity Framework Core stores a collection of complex types only as JSON: "Collections require JSON."4

When the value is large or rarely read. A large value in the owner's row is read each time the owner is read. Keep it in another table and load it with a Lazy Load.

Composite columns. SQLAlchemy says: "Sets of columns can be associated with a single user-defined datatype, which in modern use is normally a Python dataclass . The ORM provides a single attribute which represents the group of columns using the class you provide."6

Complex types and owned types. In Entity Framework Core, "A complex type groups several properties into a single .NET type that is contained within an entity type; it doesn't have an identity of its own and cannot be tracked or queried independently."4 On a relational database, "the complex type does not get its own table. Instead, its properties are saved inline as additional columns on the containing entity's table".4 Owned entity types also map, "by default", to "the same table as the owner", but they have a hidden key, and "Instances of owned entity types cannot be shared by multiple owners".7

Serialized LOB. A value that is too complex for a fixed set of columns can be saved as one serialized column. See Serialized LOB.

Dependent Mapping. When the owned objects need rows of their own, for example a list of them, the owner's mapper writes them to another table. See Dependent Mapping.

Known uses

  • SQLAlchemy: composite() maps a dataclass to a group of columns. The CompositeProperty class in descriptor_props.py at 2.0.57 defines the composite attribute, which stands for several columns as one attribute.8 Its _create_descriptor method builds the value with self.composite_class(*values) when the attribute is read, and writes each part back to its column attribute when it is set.5
  • Entity Framework Core, for .NET: complex types and owned entity types with table splitting store the properties of a value as columns of the owner's table.47
  • Java Persistence: @Embeddable classes with @Embedded fields, which the provider maps to columns of the owner's table.

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Embedded Value, pattern summary
  2. Value object, Wikipedia, lead section
  3. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 12, Object-Relational Structural Patterns, Embedded Value
  4. Entity Framework Core documentation, Complex types, introduction; A simple example; Mutability
  5. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/descriptor_props.py, CompositeProperty._create_descriptor, lines 277 to 331
  6. SQLAlchemy 2.0 documentation, Composite Column Types, introduction
  7. Entity Framework Core documentation, Owned Entity Types, Mapping owned types with table splitting; By-design restrictions
  8. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/descriptor_props.py, class CompositeProperty and its docstring, lines 185 to 190

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/Q42R2C/text.yaml