Programming Search⌘K

Patternadvanced

Dependent Mapping

Also called dependent mapping pattern, dependent object mapping, owned collection mapping.

In Dependent Mapping, the mapper of an owner class also loads, saves and deletes the child objects that belong only to that owner, such as the tracks of an album.

Family
architectural
Intent
Has one class perform the database mapping for a child class.

Intent

In a Dependent Mapping, one class "Has one class perform the database mapping for a child class."1 The child objects, the dependents, have no mapper of their own. The mapper of their owner loads, saves and deletes them with the owner.

Problem

"Some objects naturally appear in the context of other objects. Tracks on an album may be loaded or saved whenever the underlying album is loaded or saved."1 A program that gives each track its own mapper, its own key in memory and its own place in the Identity Map does work that buys nothing: no code finds a track except through its album. The program must also keep the two mappers in step, so that a track is not saved before its album or left behind when its album is deleted.

Solution

Fowler gives the condition and the step: "If they aren't referenced to by any other table in the database, you can simplify the mapping procedure by having the album mapper perform the mapping for the tracks as well".1 The owner's mapper loads the tracks when it loads the album, writes them when it saves the album, and deletes them when it deletes the album. A dependent has one owner, and nothing outside the owner refers to it.2

  memory                                  database
  Album(1, "Kind of Blue")                album(1, Kind of Blue)
    tracks = [So What, Blue in Green]     track(album_id 1, seq 1, So What)
                                          track(album_id 1, seq 2, Blue in Green)
  AlbumMapper.find(1)   -> album row + track rows of album 1
  AlbumMapper.update(a) -> update album row; delete track rows of album 1; insert them again
  AlbumMapper.delete(a) -> delete track rows of album 1; delete album row

The participants are the owner, which has an identity and a mapper; the dependents, which have no key in memory and no mapper; and the owner's mapper, which does all the database work for both. The track table has a key in the database, but it is the key of the owner and the position of the track, and the class does not need it.

The following program saves an album with two tracks, adds a track in the middle, and saves the album again.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table album (id integer primary key, title text);
create table track (album_id integer references album(id), seq integer, title text,
                    primary key (album_id, seq));
""")


class Track:  # A dependent: no key and no mapper of its own.
    def __init__(self, title):
        self.title = title


class Album:
    def __init__(self, title, tracks, id=None):
        self.id, self.title, self.tracks = id, title, tracks


class AlbumMapper:  # The owner's mapper also maps the tracks.
    def insert(self, album):
        album.id = db.execute("insert into album (title) values (?)", (album.title,)).lastrowid
        self._insert_tracks(album)

    def update(self, album):
        db.execute("update album set title = ? where id = ?", (album.title, album.id))
        db.execute("delete from track where album_id = ?", (album.id,))  # Delete all, then insert.
        self._insert_tracks(album)

    def _insert_tracks(self, album):
        rows = [(album.id, i + 1, t.title) for i, t in enumerate(album.tracks)]
        db.executemany("insert into track values (?, ?, ?)", rows)

    def find(self, id):
        (title,) = db.execute("select title from album where id = ?", (id,)).fetchone()
        sql = "select title from track where album_id = ? order by seq"
        return Album(title, [Track(t) for (t,) in db.execute(sql, (id,))], id)


mapper = AlbumMapper()
mapper.insert(Album("Kind of Blue", [Track("So What"), Track("Blue in Green")]))
album = mapper.find(1)
album.tracks.insert(1, Track("Freddie Freeloader"))
mapper.update(album)
print(db.execute("select * from track order by seq").fetchall())
Output
[(1, 1, 'So What'), (1, 2, 'Freddie Freeloader'), (1, 3, 'Blue in Green')]

Because the tracks have no identity, the mapper does not need to find out which track changed. Fowler's book describes this way to save them: delete all the rows of the dependents and insert them again.2 The order of the list becomes the seq column.

Example

Each example file inserts an album with two tracks and prints the track rows as album, position and title. It loads the album, and the tracks come with it. It then adds a track in the middle of the list and saves the album: the mapper deletes the two old rows and inserts three. The last step deletes the album, and the mapper deletes its tracks first, so no track row is left without its album. The Python file uses SQLite. The JavaScript, Java, Go and Rust files keep the two tables in memory, with the track table keyed by the album key and the position.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table album (id integer primary key, title text);
create table track (album_id integer references album(id), seq integer, title text,
                    primary key (album_id, seq));
""")


class Track:  # A dependent: no key and no mapper of its own.
    def __init__(self, title):
        self.title = title


class Album:
    def __init__(self, title, tracks, id=None):
        self.id, self.title, self.tracks = id, title, tracks


class AlbumMapper:  # The owner's mapper loads, saves and deletes the tracks.
    def insert(self, album):
        album.id = db.execute("insert into album (title) values (?)", (album.title,)).lastrowid
        return self._insert_tracks(album)

    def update(self, album):
        db.execute("update album set title = ? where id = ?", (album.title, album.id))
        deleted = db.execute("delete from track where album_id = ?", (album.id,)).rowcount
        return deleted, self._insert_tracks(album)

    def delete(self, album):
        db.execute("delete from track where album_id = ?", (album.id,))
        db.execute("delete from album where id = ?", (album.id,))

    def _insert_tracks(self, album):
        rows = [(album.id, i + 1, t.title) for i, t in enumerate(album.tracks)]
        db.executemany("insert into track values (?, ?, ?)", rows)
        return len(rows)

    def find(self, id):
        (title,) = db.execute("select title from album where id = ?", (id,)).fetchone()
        sql = "select title from track where album_id = ? order by seq"
        return Album(title, [Track(t) for (t,) in db.execute(sql, (id,))], id)


def show_tracks():
    rows = db.execute("select album_id, seq, title from track order by album_id, seq")
    return " | ".join(f"{a}/{s} {t}" for a, s, t in rows)


mapper = AlbumMapper()
mapper.insert(Album("Kind of Blue", [Track("So What"), Track("Blue in Green")]))
print("tracks:", show_tracks())

album = mapper.find(1)
print(f"loaded: {album.title} | {', '.join(t.title for t in album.tracks)}")

album.tracks.insert(1, Track("Freddie Freeloader"))
deleted, inserted = mapper.update(album)
print(f"update: deleted {deleted}, inserted {inserted}")
print("tracks:", show_tracks())

mapper.delete(album)
(albums,) = db.execute("select count(*) from album").fetchone()
(tracks,) = db.execute("select count(*) from track").fetchone()
print(f"delete album 1: albums {albums}, tracks {tracks}")
Output
tracks: 1/1 So What | 1/2 Blue in Green
loaded: Kind of Blue | So What, Blue in Green
update: deleted 2, inserted 3
tracks: 1/1 So What | 1/2 Freddie Freeloader | 1/3 Blue in Green
delete album 1: albums 0, tracks 0
  • Verdict: idiom. Track has no key and no mapper. AlbumMapper writes the tracks with the album, with (album_id, seq) as the key of the track table, so the position in the list is part of the key.
  • update deletes all the track rows of the album and inserts the list again, and delete removes the tracks before the album.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    record TrackKey(long albumId, int seq) implements Comparable<TrackKey> {
        public int compareTo(TrackKey o) {
            int c = Long.compare(albumId, o.albumId);
            return c != 0 ? c : Integer.compare(seq, o.seq);
        }
    }

    // A stand-in for the database: an album table, and a track table keyed by (album_id, seq).
    static final Map<Long, String> ALBUM = new TreeMap<>();
    static final TreeMap<TrackKey, String> TRACK = new TreeMap<>();
    static long lastAlbum = 0;

    // A dependent: no key and no mapper of its own.
    record Track(String title) {}

    static class Album {
        Long id;
        String title;
        List<Track> tracks;

        Album(String title, List<Track> tracks, Long id) {
            this.title = title;
            this.tracks = tracks;
            this.id = id;
        }
    }

    // The owner's mapper loads, saves and deletes the tracks.
    static class AlbumMapper {
        int insert(Album album) {
            ALBUM.put(++lastAlbum, album.title);
            album.id = lastAlbum;
            return insertTracks(album);
        }

        int[] update(Album album) {
            ALBUM.put(album.id, album.title);
            int deleted = deleteTracks(album.id);
            return new int[] {deleted, insertTracks(album)};
        }

        void delete(Album album) {
            deleteTracks(album.id);
            ALBUM.remove(album.id);
        }

        int insertTracks(Album album) {
            for (int i = 0; i < album.tracks.size(); i++) {
                TRACK.put(new TrackKey(album.id, i + 1), album.tracks.get(i).title());
            }
            return album.tracks.size();
        }

        int deleteTracks(long albumId) {
            Map<TrackKey, String> rows = TRACK.subMap(new TrackKey(albumId, 0), new TrackKey(albumId + 1, 0));
            int n = rows.size();
            rows.clear();
            return n;
        }

        Album find(long id) {
            List<Track> tracks = new ArrayList<>();
            TRACK.subMap(new TrackKey(id, 0), new TrackKey(id + 1, 0)).values().forEach(t -> tracks.add(new Track(t)));
            return new Album(ALBUM.get(id), tracks, id);
        }
    }

    static String showTracks() {
        List<String> parts = new ArrayList<>();
        TRACK.forEach((k, t) -> parts.add(k.albumId() + "/" + k.seq() + " " + t));
        return String.join(" | ", parts);
    }

    public static void main(String[] args) {
        AlbumMapper mapper = new AlbumMapper();
        mapper.insert(new Album("Kind of Blue", new ArrayList<>(List.of(new Track("So What"), new Track("Blue in Green"))), null));
        System.out.println("tracks: " + showTracks());

        Album album = mapper.find(1);
        List<String> titles = new ArrayList<>();
        album.tracks.forEach(t -> titles.add(t.title()));
        System.out.println("loaded: " + album.title + " | " + String.join(", ", titles));

        album.tracks.add(1, new Track("Freddie Freeloader"));
        int[] counts = mapper.update(album);
        System.out.println("update: deleted " + counts[0] + ", inserted " + counts[1]);
        System.out.println("tracks: " + showTracks());

        mapper.delete(album);
        System.out.println("delete album 1: albums " + ALBUM.size() + ", tracks " + TRACK.size());
    }
}
Output
tracks: 1/1 So What | 1/2 Blue in Green
loaded: Kind of Blue | So What, Blue in Green
update: deleted 2, inserted 3
tracks: 1/1 So What | 1/2 Freddie Freeloader | 1/3 Blue in Green
delete album 1: albums 0, tracks 0
  • Verdict: idiom. The key of a track row is a TrackKey record that is Comparable, so the TreeMap keeps the rows in album and position order. Track is a record with only a title.
  • With JPA or Hibernate, @ElementCollection with @OrderColumn maps the same list, and the provider can delete and insert the rows of the collection when it changes.
JavaScriptGitHub
// A stand-in for the database: an album table, and a track table keyed by "albumId/seq".
const albumTable = new Map();
const trackTable = new Map();
let lastAlbum = 0;

class Track {
  // A dependent: no key and no mapper of its own.
  constructor(title) {
    this.title = title;
  }
}

class Album {
  constructor(title, tracks, id = null) {
    this.id = id;
    this.title = title;
    this.tracks = tracks;
  }
}

class AlbumMapper {
  // The owner's mapper loads, saves and deletes the tracks.
  insert(album) {
    lastAlbum += 1;
    albumTable.set(lastAlbum, album.title);
    album.id = lastAlbum;
    return this.insertTracks(album);
  }

  update(album) {
    albumTable.set(album.id, album.title);
    return [this.deleteTracks(album.id), this.insertTracks(album)];
  }

  delete(album) {
    this.deleteTracks(album.id);
    albumTable.delete(album.id);
  }

  insertTracks(album) {
    album.tracks.forEach((t, i) => trackTable.set(`${album.id}/${i + 1}`, t.title));
    return album.tracks.length;
  }

  deleteTracks(albumId) {
    const keys = [...trackTable.keys()].filter((k) => k.startsWith(`${albumId}/`));
    for (const k of keys) trackTable.delete(k);
    return keys.length;
  }

  find(id) {
    const tracks = trackRows()
      .filter(([a]) => a === id)
      .map(([, , title]) => new Track(title));
    return new Album(albumTable.get(id), tracks, id);
  }
}

function trackRows() {
  return [...trackTable]
    .map(([k, title]) => [...k.split("/").map(Number), title])
    .sort((x, y) => x[0] - y[0] || x[1] - y[1]);
}

function showTracks() {
  return trackRows()
    .map(([a, s, t]) => `${a}/${s} ${t}`)
    .join(" | ");
}

const mapper = new AlbumMapper();
mapper.insert(new Album("Kind of Blue", [new Track("So What"), new Track("Blue in Green")]));
console.log(`tracks: ${showTracks()}`);

const album = mapper.find(1);
console.log(`loaded: ${album.title} | ${album.tracks.map((t) => t.title).join(", ")}`);

album.tracks.splice(1, 0, new Track("Freddie Freeloader"));
const [deleted, inserted] = mapper.update(album);
console.log(`update: deleted ${deleted}, inserted ${inserted}`);
console.log(`tracks: ${showTracks()}`);

mapper.delete(album);
console.log(`delete album 1: albums ${albumTable.size}, tracks ${trackTable.size}`);
Output
tracks: 1/1 So What | 1/2 Blue in Green
loaded: Kind of Blue | So What, Blue in Green
update: deleted 2, inserted 3
tracks: 1/1 So What | 1/2 Freddie Freeloader | 1/3 Blue in Green
delete album 1: albums 0, tracks 0
  • Verdict: idiom. The track table is a Map keyed by the string "albumId/seq", and Track holds only a title.
  • deleteTracks collects the keys of the album first and then deletes them, so the loop does not change the map that it reads.
package main

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

type trackKey struct {
	albumID int64
	seq     int
}

// A stand-in for the database: an album table, and a track table keyed by (album_id, seq).
var (
	albumTable = map[int64]string{}
	trackTable = map[trackKey]string{}
	lastAlbum  int64
)

// Track is a dependent: no key and no mapper of its own.
type Track struct{ Title string }

type Album struct {
	ID     int64
	Title  string
	Tracks []Track
}

// AlbumMapper is the owner's mapper: it loads, saves and deletes the tracks.
type AlbumMapper struct{}

func (m AlbumMapper) Insert(a *Album) int {
	lastAlbum++
	albumTable[lastAlbum] = a.Title
	a.ID = lastAlbum
	return m.insertTracks(a)
}

func (m AlbumMapper) Update(a *Album) (deleted, inserted int) {
	albumTable[a.ID] = a.Title
	deleted = m.deleteTracks(a.ID)
	return deleted, m.insertTracks(a)
}

func (m AlbumMapper) Delete(a *Album) {
	m.deleteTracks(a.ID)
	delete(albumTable, a.ID)
}

func (m AlbumMapper) insertTracks(a *Album) int {
	for i, t := range a.Tracks {
		trackTable[trackKey{a.ID, i + 1}] = t.Title
	}
	return len(a.Tracks)
}

func (m AlbumMapper) deleteTracks(albumID int64) int {
	n := 0
	for k := range trackTable {
		if k.albumID == albumID {
			delete(trackTable, k)
			n++
		}
	}
	return n
}

func (m AlbumMapper) Find(id int64) *Album {
	var tracks []Track
	for _, k := range trackKeys() {
		if k.albumID == id {
			tracks = append(tracks, Track{trackTable[k]})
		}
	}
	return &Album{id, albumTable[id], tracks}
}

func trackKeys() []trackKey {
	keys := make([]trackKey, 0, len(trackTable))
	for k := range trackTable {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool {
		if keys[i].albumID != keys[j].albumID {
			return keys[i].albumID < keys[j].albumID
		}
		return keys[i].seq < keys[j].seq
	})
	return keys
}

func showTracks() string {
	var parts []string
	for _, k := range trackKeys() {
		parts = append(parts, fmt.Sprintf("%d/%d %s", k.albumID, k.seq, trackTable[k]))
	}
	return strings.Join(parts, " | ")
}

func main() {
	mapper := AlbumMapper{}
	mapper.Insert(&Album{Title: "Kind of Blue", Tracks: []Track{{"So What"}, {"Blue in Green"}}})
	fmt.Println("tracks:", showTracks())

	album := mapper.Find(1)
	var titles []string
	for _, t := range album.Tracks {
		titles = append(titles, t.Title)
	}
	fmt.Printf("loaded: %s | %s\n", album.Title, strings.Join(titles, ", "))

	album.Tracks = append(album.Tracks[:1], append([]Track{{"Freddie Freeloader"}}, album.Tracks[1:]...)...)
	deleted, inserted := mapper.Update(album)
	fmt.Printf("update: deleted %d, inserted %d\n", deleted, inserted)
	fmt.Println("tracks:", showTracks())

	mapper.Delete(album)
	fmt.Printf("delete album 1: albums %d, tracks %d\n", len(albumTable), len(trackTable))
}
Output
tracks: 1/1 So What | 1/2 Blue in Green
loaded: Kind of Blue | So What, Blue in Green
update: deleted 2, inserted 3
tracks: 1/1 So What | 1/2 Freddie Freeloader | 1/3 Blue in Green
delete album 1: albums 0, tracks 0
  • Verdict: idiom. The key of a track row is a trackKey struct of the album key and the position. Go maps have no order, so trackKeys sorts the keys before the program prints the rows.
  • Update returns the counts of the deleted and inserted rows, and Delete removes the tracks before the album.
RustGitHub
use std::collections::BTreeMap;

// A dependent: no key and no mapper of its own.
struct Track {
    title: String,
}

struct Album {
    id: Option<i64>,
    title: String,
    tracks: Vec<Track>,
}

fn track(title: &str) -> Track {
    Track { title: title.to_string() }
}

// A stand-in for the database: an album table, and a track table keyed by (album_id, seq).
#[derive(Default)]
struct Db {
    album: BTreeMap<i64, String>,
    track: BTreeMap<(i64, usize), String>,
    last_album: i64,
}

// The owner's mapper loads, saves and deletes the tracks.
struct AlbumMapper;

impl AlbumMapper {
    fn insert(&self, db: &mut Db, album: &mut Album) -> usize {
        db.last_album += 1;
        db.album.insert(db.last_album, album.title.clone());
        album.id = Some(db.last_album);
        self.insert_tracks(db, db.last_album, album)
    }

    fn update(&self, db: &mut Db, album: &Album) -> (usize, usize) {
        let id = album.id.expect("the album is saved");
        db.album.insert(id, album.title.clone());
        let deleted = self.delete_tracks(db, id);
        (deleted, self.insert_tracks(db, id, album))
    }

    fn delete(&self, db: &mut Db, album: &Album) {
        if let Some(id) = album.id {
            self.delete_tracks(db, id);
            db.album.remove(&id);
        }
    }

    fn insert_tracks(&self, db: &mut Db, id: i64, album: &Album) -> usize {
        for (i, t) in album.tracks.iter().enumerate() {
            db.track.insert((id, i + 1), t.title.clone());
        }
        album.tracks.len()
    }

    fn delete_tracks(&self, db: &mut Db, id: i64) -> usize {
        let before = db.track.len();
        db.track.retain(|(album_id, _), _| *album_id != id);
        before - db.track.len()
    }

    fn find(&self, db: &Db, id: i64) -> Album {
        let tracks = db.track.range((id, 0)..(id + 1, 0)).map(|(_, t)| track(t)).collect();
        Album { id: Some(id), title: db.album[&id].clone(), tracks }
    }
}

fn show_tracks(db: &Db) -> String {
    let parts: Vec<String> = db.track.iter().map(|((a, s), t)| format!("{}/{} {}", a, s, t)).collect();
    parts.join(" | ")
}

fn main() {
    let mut db = Db::default();
    let mapper = AlbumMapper;
    let mut kind_of_blue = Album {
        id: None,
        title: "Kind of Blue".to_string(),
        tracks: vec![track("So What"), track("Blue in Green")],
    };
    mapper.insert(&mut db, &mut kind_of_blue);
    println!("tracks: {}", show_tracks(&db));

    let mut album = mapper.find(&db, 1);
    let titles: Vec<&str> = album.tracks.iter().map(|t| t.title.as_str()).collect();
    println!("loaded: {} | {}", album.title, titles.join(", "));

    album.tracks.insert(1, track("Freddie Freeloader"));
    let (deleted, inserted) = mapper.update(&mut db, &album);
    println!("update: deleted {}, inserted {}", deleted, inserted);
    println!("tracks: {}", show_tracks(&db));

    mapper.delete(&mut db, &album);
    println!("delete album 1: albums {}, tracks {}", db.album.len(), db.track.len());
}
Output
tracks: 1/1 So What | 1/2 Blue in Green
loaded: Kind of Blue | So What, Blue in Green
update: deleted 2, inserted 3
tracks: 1/1 So What | 1/2 Freddie Freeloader | 1/3 Blue in Green
delete album 1: albums 0, tracks 0
  • Verdict: idiom. The track table is a BTreeMap<(i64, usize), String>, so the rows iterate in album and position order.
  • delete_tracks uses retain to remove the rows of one album and returns the number of removed rows.

Consequences

Benefits.

  • Less mapping code. One mapper does the work, and the dependents need no mapper, no key field and no entry in the identity map.
  • The owner and its dependents stay consistent. They load together, save together and are deleted together, so the program never sees an album with part of its tracks.
  • A simple save. Delete all and insert again needs no tracking of changes in the collection.

Liabilities.

The rule breaks when something else refers to a dependent. Delete all and insert again gives the rows new keys. If another table refers to a dependent by its key, that reference now points to a row with other data, or to no row at all. In the following program, a playlist refers to the track Blue in Green by its key 2. The user moves that track to the top of the album, the mapper saves the tracks by delete and insert, and the playlist now points to So What.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table track (id integer primary key, album_id integer, title text);
create table playlist_entry (playlist text, track_id integer references track(id));
insert into track (album_id, title) values (1, 'So What'), (1, 'Blue in Green');
-- A second table refers to a track, so the track is no longer a dependent.
insert into playlist_entry values ('Evening', 2);
""")

# The user moves Blue in Green to the top. The album mapper saves the tracks
# of album 1 by delete all, then insert, and the rows get new keys.
db.execute("delete from track where album_id = 1")
db.executemany("insert into track (album_id, title) values (1, ?)", [("Blue in Green",), ("So What",)])

sql = "select p.playlist, p.track_id, t.title from playlist_entry p left join track t on t.id = p.track_id"
print(db.execute(sql).fetchall())
Output
[('Evening', 2, 'So What')]

If something outside the owner must refer to the child, the child is no longer a dependent. Give it an identity, a mapper and a Foreign Key Mapping of its own, and save changes to it row by row.

Many writes for a small change. Changing the title of one track rewrites all the rows of the album. For large collections, compare the collection with the rows instead, as a Unit of Work does.

All dependents load with the owner. The owner's mapper loads the whole collection each time. Entity Framework Core does the same: "When querying the owner the owned types will be included by default."3

When not to use it

When the child is referenced from outside. This is the condition in Fowler's summary. A track that a playlist or a sales table refers to is an entity, not a dependent.

When the child is shared. A dependent has one owner. A child that two owners hold, such as a skill of many employees, needs its own table and an Association Table Mapping.

When the child is a single small value. A value with a fixed set of fields fits in columns of the owner's row. Use an Embedded Value.

Owned entity types. In Entity Framework Core, "Owned entities are essentially a part of the owner and cannot exist without it, they are conceptually similar to aggregates ."3 "To configure a collection of owned types use OwnsMany in OnModelCreating ." By default, the key of an owned collection is the owner's key plus another property, and so "the relationship between the owner and the owned entity becomes immutable and reflects aggregate semantics better."3

Delete-orphan cascades. An ORM that maps the child as a class of its own can still give it the life cycle of a dependent. In SQLAlchemy, "delete-orphan cascade adds behavior to the delete cascade, such that a child object will be marked for deletion when it is de-associated from the parent, not just when the parent is marked for deletion." It "implies that each child object can only have one parent at a time".4

Aggregates. In domain-driven design, an aggregate is a group of objects that change together through one root. The root's mapper and its dependents are a way to save an aggregate.

Embedded Value. An embedded value is a dependent that is stored in the owner's row. See Embedded Value.

Known uses

  • SQLAlchemy: a relationship() with the delete-orphan cascade. In OneToManyDP.presort_saves in dependency.py at 2.0.57, each child that was removed from the collection and has no parent is registered for deletion with isdelete=True when self.cascade.delete_orphan is set.5
  • Entity Framework Core, for .NET: OwnsMany maps a collection of owned types to a table whose key includes the owner's key, and the owner's queries include it.3
  • Java Persistence: @ElementCollection maps a collection of embeddable objects to a table that the owner's entity manages, and orphanRemoval = true on a one-to-many association deletes the children that leave the collection.

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Dependent Mapping, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 12, Object-Relational Structural Patterns, Dependent Mapping
  3. Entity Framework Core documentation, Owned Entity Types, introduction; Collections of owned types; Querying owned types
  4. SQLAlchemy 2.0 documentation, Cascades, delete-orphan
  5. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/dependency.py, OneToManyDP.presort_saves, lines 466 to 520

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/GV1SJG/text.yaml