Programming Search⌘K

Patterncore

Identity Map

Also called identity map pattern, identity resolution, first-level cache.

An Identity Map keeps each object that a session loads from the database in a map by its key, so that one row has only one object in memory and is not loaded twice.

Family
architectural
Intent
Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them.

Intent

An Identity Map "Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them."1 In one session, one database row has one object in memory, however many times and by whatever query the program reads it.

Problem

Two parts of a program read the same row, for example the customer of an order and the customer of an invoice. If each read makes a new object, the program has two objects for one row. Fowler's catalogue says: "If you aren't careful you can load the data from the same database record into two different objects. Then, when you update them both you'll have an interesting time writing the changes out to the database correctly."1

Each part changes its own copy and saves it, and the last save wins. The change of the other part is lost, and no error is reported.

There is also a cost. "If you load the same data more than once you're incurring an expensive cost in remote calls."1

Solution

Give each session a map from the primary key to the loaded object. Before a mapper loads a row by its key, it looks in the map. When a query returns rows, the mapper looks up the key of each row. If the map has an object for the key, the mapper returns that object and does not make a new one. Otherwise it makes the object and puts it in the map. "Whenever you want an object, you check the Identity Map first to see if you already have it."12

  caller                    PersonMapper                         database
  find(1)  ---------------> map has 1?  no  --------------------> SELECT ... WHERE id = 1
                            make Person 1, map[1] = it
  find(1)  ---------------> map has 1?  yes: return map[1]        (no query)
  find_by_city("Oslo") ---> query by city ----------------------> SELECT ... WHERE city = 'Oslo'
                            row 1: map has 1? yes: return map[1]
                            row 2: map has 2? no: make Person 2, map[2] = it

The participants are the identity map, which is usually keyed by the table or class and the primary key; the mappers or the session, which use it on every load; and the callers, which get the same object for the same row.

The following program uses SQLite. The second find(1) runs no query. The query by city must run, because the map is keyed by id, but it returns the object that the map already has. That object keeps a change that is not saved yet, so a query for the people in Oslo returns Ann with the city Rome. A second mapper, which stands for another session, has its own map and loads its own object.

import sqlite3


class Person:
    def __init__(self, id, name, city):
        self.id, self.name, self.city = id, name, city


class PersonMapper:
    """Loads people. Its identity map holds one object for each primary key."""

    def __init__(self, db):
        self.db = db
        self.identity_map = {}
        self.selects = 0

    def find(self, id):
        if id in self.identity_map:  # already loaded: no query
            return self.identity_map[id]
        self.selects += 1
        row = self.db.execute("SELECT id, name, city FROM people WHERE id = ?", (id,)).fetchone()
        return None if row is None else self._load(row)

    def find_by_city(self, city):
        self.selects += 1  # the map is keyed by id, so a query by city must run
        rows = self.db.execute("SELECT id, name, city FROM people WHERE city = ? ORDER BY id", (city,))
        return [self._load(row) for row in rows]

    def _load(self, row):
        person = self.identity_map.get(row[0])
        if person is None:  # a new object only for a key that is not in the map
            person = Person(*row)
            self.identity_map[row[0]] = person
        return person


db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT, city TEXT)")
db.executemany("INSERT INTO people VALUES (?, ?, ?)", [(1, "Ann", "Oslo"), (2, "Bo", "Oslo"), (3, "Cy", "Bergen")])

mapper = PersonMapper(db)  # one mapper, and one map, for each session
a = mapper.find(1)
b = mapper.find(1)
print("a is b:", a is b, "| selects:", mapper.selects)

oslo = mapper.find_by_city("Oslo")
print("Oslo:", [p.name for p in oslo], "| oslo[0] is a:", oslo[0] is a, "| selects:", mapper.selects)

a.city = "Rome"  # a change in memory, not saved yet
print("b.city:", b.city)
print("Oslo again:", [(p.name, p.city) for p in mapper.find_by_city("Oslo")])

other = PersonMapper(db)  # another session has its own map
print("other session:", other.find(1) is a, other.find(1).city)
Output
a is b: True | selects: 1
Oslo: ['Ann', 'Bo'] | oslo[0] is a: True | selects: 2
b.city: Rome
Oslo again: [('Ann', 'Rome'), ('Bo', 'Oslo')]
other session: False Oslo

The ORMs behave in the same way. SQLAlchemy says that when two queries return the same row, "the two queries will have returned the same Python object", and that the ORM "will skip the population of attributes for an object that's already loaded."3 Doctrine documents the result of the last query above: "if the query finds the article by its old headline, the returned instance contains the modified headline."4

Example

Each example file has a Person class and a PersonMapper with find and find_by_city and a map from the id to the object. The program reads the same row twice, runs a query by city, changes an object, and makes a second mapper for another session. The Python file uses SQLite, and its map is a weakref.WeakValueDictionary, so the map does not keep objects alive. The JavaScript, Java, Go and Rust files keep the table in memory and count each read as one SELECT, because the standard libraries of these languages have no database driver. Each file compares objects by identity: is in Python, === in JavaScript, == on references in Java and on pointers in Go, and Rc::ptr_eq in Rust.

PythonGitHub
import gc
import sqlite3
import weakref


class Person:
    def __init__(self, id, name, city):
        self.id, self.name, self.city = id, name, city


class PersonMapper:
    def __init__(self, db):
        self.db = db
        # The map does not keep objects alive. When the program drops the last
        # reference to an object, its entry goes away.
        self.identity_map = weakref.WeakValueDictionary()
        self.selects = 0

    def find(self, id):
        person = self.identity_map.get(id)
        if person is not None:
            return person
        self.selects += 1
        row = self.db.execute("SELECT id, name, city FROM people WHERE id = ?", (id,)).fetchone()
        return None if row is None else self._load(row)

    def find_by_city(self, city):
        self.selects += 1
        rows = self.db.execute("SELECT id, name, city FROM people WHERE city = ? ORDER BY id", (city,))
        return [self._load(row) for row in rows]

    def _load(self, row):
        person = self.identity_map.get(row[0])
        if person is None:
            person = Person(*row)
            self.identity_map[row[0]] = person
        return person


db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT, city TEXT)")
db.executemany("INSERT INTO people VALUES (?, ?, ?)", [(1, "Ann", "Oslo"), (2, "Bo", "Oslo"), (3, "Cy", "Bergen")])

mapper = PersonMapper(db)
a, b = mapper.find(1), mapper.find(1)
print("a is b:", a is b, "| selects:", mapper.selects)
oslo = mapper.find_by_city("Oslo")
print("Oslo:", ", ".join(p.name for p in oslo), "| oslo[0] is a:", oslo[0] is a, "| selects:", mapper.selects)
a.city = "Rome"
print("b.city:", b.city)
print("Oslo again:", ", ".join(f"{p.name} in {p.city}" for p in mapper.find_by_city("Oslo")))
print("another session: same object:", PersonMapper(db).find(1) is a)

print("keys in the map:", sorted(mapper.identity_map.keys()))
del a, b, oslo  # the program no longer uses these objects
gc.collect()
print("keys in the map:", sorted(mapper.identity_map.keys()))
print("find(1) again:", mapper.find(1).city, "| selects:", mapper.selects)
Output
a is b: True | selects: 1
Oslo: Ann, Bo | oslo[0] is a: True | selects: 2
b.city: Rome
Oslo again: Ann in Rome, Bo in Oslo
another session: same object: False
keys in the map: [1, 2]
keys in the map: []
find(1) again: Oslo | selects: 4
  • Verdict: idiom. A weakref.WeakValueDictionary does not keep its values alive, so the map holds only the objects that the program still uses. SQLAlchemy keeps the objects of a Session in the same way.
  • After del, the map is empty, and the next find(1) runs a query and returns a new object with the city from the table. The change to Rome was never saved, so it is gone. SQLAlchemy keeps a strong reference to an object that has pending changes for this reason.
JavaGitHub
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Main {
    static final class Person {
        final long id;
        String name, city;

        Person(long id, String name, String city) {
            this.id = id;
            this.name = name;
            this.city = city;
        }
    }

    record PersonRow(long id, String name, String city) {}

    // A stand-in for the people table, because the JDK has JDBC but no database driver.
    // Each call of select() stands for one SELECT statement.
    static final class Database {
        final List<PersonRow> rows = List.of(new PersonRow(1, "Ann", "Oslo"), new PersonRow(2, "Bo", "Oslo"), new PersonRow(3, "Cy", "Bergen"));
        int selects;

        List<PersonRow> select(Predicate<PersonRow> where) {
            selects++;
            return rows.stream().filter(where).toList();
        }
    }

    static final class PersonMapper {
        private final Database db;
        private final Map<Long, Person> identityMap = new HashMap<>(); // primary key -> the one object for that row

        PersonMapper(Database db) {
            this.db = db;
        }

        Optional<Person> find(long id) {
            var known = identityMap.get(id);
            if (known != null) return Optional.of(known); // no query
            return db.select(r -> r.id() == id).stream().findFirst().map(this::load);
        }

        List<Person> findByCity(String city) {
            // The map is keyed by id, so a query by city must run.
            return db.select(r -> r.city().equals(city)).stream().map(this::load).toList();
        }

        private Person load(PersonRow row) {
            return identityMap.computeIfAbsent(row.id(), id -> new Person(id, row.name(), row.city()));
        }
    }

    public static void main(String[] args) {
        var db = new Database();
        var mapper = new PersonMapper(db); // one mapper, and one map, for each session
        var a = mapper.find(1).orElseThrow();
        var b = mapper.find(1).orElseThrow();
        System.out.println("a == b: " + (a == b) + " | selects: " + db.selects);

        var oslo = mapper.findByCity("Oslo");
        System.out.println("Oslo: " + oslo.stream().map(p -> p.name).collect(Collectors.joining(", "))
                + " | oslo.get(0) == a: " + (oslo.get(0) == a) + " | selects: " + db.selects);

        a.city = "Rome"; // a change in memory, not saved yet
        System.out.println("b.city: " + b.city);
        System.out.println("Oslo again: " + mapper.findByCity("Oslo").stream()
                .map(p -> p.name + " in " + p.city).collect(Collectors.joining(", ")));
        System.out.println("another session: same object: " + (new PersonMapper(db).find(1).orElseThrow() == a));
    }
}
Output
a == b: true | selects: 1
Oslo: Ann, Bo | oslo.get(0) == a: true | selects: 2
b.city: Rome
Oslo again: Ann in Rome, Bo in Oslo
another session: same object: false
  • Verdict: idiom. computeIfAbsent makes the object only for a key that is not yet in the map, and == on two references compares identity.
  • The map belongs to one PersonMapper, so the mapper of another session loads a second object for the same row, as the last line shows.
JavaScriptGitHub
class Person {
  constructor(id, name, city) {
    Object.assign(this, { id, name, city });
  }
}

// A stand-in for the people table, because Node has no SQL driver in its standard library.
// Each call of select() stands for one SELECT statement, and returns fresh row objects.
class Database {
  rows = [[1, "Ann", "Oslo"], [2, "Bo", "Oslo"], [3, "Cy", "Bergen"]];
  selects = 0;

  select(where) {
    this.selects++;
    return this.rows.filter(where).map((row) => [...row]);
  }
}

class PersonMapper {
  #identityMap = new Map(); // primary key -> the one object for that row

  constructor(db) {
    this.db = db;
  }

  find(id) {
    if (this.#identityMap.has(id)) return this.#identityMap.get(id); // no query
    const [row] = this.db.select(([rowId]) => rowId === id);
    return row === undefined ? undefined : this.#load(row);
  }

  findByCity(city) {
    // The map is keyed by id, so a query by city must run.
    return this.db.select(([, , rowCity]) => rowCity === city).map((row) => this.#load(row));
  }

  #load([id, name, city]) {
    let person = this.#identityMap.get(id);
    if (person === undefined) {
      person = new Person(id, name, city);
      this.#identityMap.set(id, person);
    }
    return person;
  }
}

const db = new Database();
const mapper = new PersonMapper(db); // one mapper, and one map, for each session
const a = mapper.find(1);
const b = mapper.find(1);
console.log(`a === b: ${a === b} | selects: ${db.selects}`);

const oslo = mapper.findByCity("Oslo");
console.log(`Oslo: ${oslo.map((p) => p.name).join(", ")} | oslo[0] === a: ${oslo[0] === a} | selects: ${db.selects}`);

a.city = "Rome"; // a change in memory, not saved yet
console.log(`b.city: ${b.city}`);
console.log(`Oslo again: ${mapper.findByCity("Oslo").map((p) => `${p.name} in ${p.city}`).join(", ")}`);
console.log(`another session: same object: ${new PersonMapper(db).find(1) === a}`);
Output
a === b: true | selects: 1
Oslo: Ann, Bo | oslo[0] === a: true | selects: 2
b.city: Rome
Oslo again: Ann in Rome, Bo in Oslo
another session: same object: false
  • Verdict: idiom. A Map from the primary key to the object is the identity map, and === on two objects compares references.
  • The query by city runs, because the map knows objects only by key, but #load returns the object that is already in the map, with its unsaved city.
package main

import (
	"fmt"
	"strings"
)

type Person struct {
	ID         int
	Name, City string
}

// A stand-in for the people table. The Go standard library has database/sql,
// but no driver for a real database. Each call of Select stands for one SELECT statement.
type personRow struct {
	id         int
	name, city string
}

type Database struct {
	rows    []personRow
	Selects int
}

func (db *Database) Select(where func(personRow) bool) []personRow {
	db.Selects++
	var out []personRow
	for _, r := range db.rows {
		if where(r) {
			out = append(out, r)
		}
	}
	return out
}

type PersonMapper struct {
	db          *Database
	identityMap map[int]*Person // primary key -> the one object for that row
}

func NewPersonMapper(db *Database) *PersonMapper {
	return &PersonMapper{db, map[int]*Person{}}
}

func (m *PersonMapper) Find(id int) (*Person, bool) {
	if p, ok := m.identityMap[id]; ok {
		return p, true // no query
	}
	rows := m.db.Select(func(r personRow) bool { return r.id == id })
	if len(rows) == 0 {
		return nil, false
	}
	return m.load(rows[0]), true
}

func (m *PersonMapper) FindByCity(city string) []*Person {
	// The map is keyed by id, so a query by city must run.
	var people []*Person
	for _, r := range m.db.Select(func(r personRow) bool { return r.city == city }) {
		people = append(people, m.load(r))
	}
	return people
}

func (m *PersonMapper) load(r personRow) *Person {
	p, ok := m.identityMap[r.id]
	if !ok {
		p = &Person{r.id, r.name, r.city}
		m.identityMap[r.id] = p
	}
	return p
}

func describe(people []*Person, withCity bool) string {
	var parts []string
	for _, p := range people {
		if withCity {
			parts = append(parts, p.Name+" in "+p.City)
		} else {
			parts = append(parts, p.Name)
		}
	}
	return strings.Join(parts, ", ")
}

func main() {
	db := &Database{rows: []personRow{{1, "Ann", "Oslo"}, {2, "Bo", "Oslo"}, {3, "Cy", "Bergen"}}}
	mapper := NewPersonMapper(db) // one mapper, and one map, for each session
	a, _ := mapper.Find(1)
	b, _ := mapper.Find(1)
	fmt.Printf("a == b: %t | selects: %d\n", a == b, db.Selects)

	oslo := mapper.FindByCity("Oslo")
	fmt.Printf("Oslo: %s | oslo[0] == a: %t | selects: %d\n", describe(oslo, false), oslo[0] == a, db.Selects)

	a.City = "Rome" // a change in memory, not saved yet
	fmt.Println("b.City:", b.City)
	fmt.Println("Oslo again:", describe(mapper.FindByCity("Oslo"), true))
	other, _ := NewPersonMapper(db).Find(1)
	fmt.Println("another session: same object:", other == a)
}
Output
a == b: true | selects: 1
Oslo: Ann, Bo | oslo[0] == a: true | selects: 2
b.City: Rome
Oslo again: Ann in Rome, Bo in Oslo
another session: same object: false
  • Verdict: idiom. The map holds *Person values, so all callers share one struct for each row, and == on two pointers compares identity.
  • A map of struct values in place of pointers would copy each struct on every read, and the change to City would not reach the other callers.
RustGitHub
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

struct Person {
    id: u32,
    name: String,
    city: String,
}

// Rc gives shared ownership, RefCell lets the program change a shared object,
// and Rc::ptr_eq compares identity.
type PersonRef = Rc<RefCell<Person>>;

// A stand-in for the people table, because the standard library has no driver.
// Each call of select() stands for one SELECT statement.
struct Database {
    rows: Vec<(u32, &'static str, &'static str)>,
    selects: Cell<u32>,
}

impl Database {
    fn select(&self, filter: impl Fn(&(u32, &str, &str)) -> bool) -> Vec<(u32, &'static str, &'static str)> {
        self.selects.set(self.selects.get() + 1);
        self.rows.iter().filter(|r| filter(r)).copied().collect()
    }
}

struct PersonMapper<'a> {
    db: &'a Database,
    identity_map: HashMap<u32, PersonRef>, // primary key -> the one object for that row
}

impl<'a> PersonMapper<'a> {
    fn new(db: &'a Database) -> Self {
        PersonMapper { db, identity_map: HashMap::new() }
    }

    fn find(&mut self, id: u32) -> Option<PersonRef> {
        if let Some(p) = self.identity_map.get(&id) {
            return Some(Rc::clone(p)); // no query
        }
        let row = self.db.select(|r| r.0 == id).into_iter().next()?;
        Some(self.load(row))
    }

    fn find_by_city(&mut self, city: &str) -> Vec<PersonRef> {
        // The map is keyed by id, so a query by city must run.
        self.db.select(|r| r.2 == city).into_iter().map(|row| self.load(row)).collect()
    }

    fn load(&mut self, (id, name, city): (u32, &str, &str)) -> PersonRef {
        let person = self
            .identity_map
            .entry(id)
            .or_insert_with(|| Rc::new(RefCell::new(Person { id, name: name.into(), city: city.into() })));
        Rc::clone(person)
    }
}

fn main() {
    let db = Database {
        rows: vec![(1, "Ann", "Oslo"), (2, "Bo", "Oslo"), (3, "Cy", "Bergen")],
        selects: Cell::new(0),
    };
    let mut mapper = PersonMapper::new(&db); // one mapper, and one map, for each session
    let a = mapper.find(1).unwrap();
    let b = mapper.find(1).unwrap();
    println!("Rc::ptr_eq(&a, &b): {} | selects: {}", Rc::ptr_eq(&a, &b), db.selects.get());

    let oslo = mapper.find_by_city("Oslo");
    let names: Vec<String> = oslo.iter().map(|p| p.borrow().name.clone()).collect();
    println!("Oslo: {} | oslo[0] is a: {} | selects: {}", names.join(", "), Rc::ptr_eq(&oslo[0], &a), db.selects.get());

    a.borrow_mut().city = "Rome".into(); // a change in memory, not saved yet
    println!("b.city: {}", b.borrow().city);
    let again: Vec<String> = mapper
        .find_by_city("Oslo")
        .iter()
        .map(|p| format!("{} in {}", p.borrow().name, p.borrow().city))
        .collect();
    println!("Oslo again: {}", again.join(", "));
    let other = PersonMapper::new(&db).find(1).unwrap();
    println!("another session: same object: {} (id {})", Rc::ptr_eq(&other, &a), other.borrow().id);
}
Output
Rc::ptr_eq(&a, &b): true | selects: 1
Oslo: Ann, Bo | oslo[0] is a: true | selects: 2
b.city: Rome
Oslo again: Ann in Rome, Bo in Oslo
another session: same object: false (id 1)
  • Verdict: idiom. The map holds Rc<RefCell<Person>>, so all callers share one object and can change it, and Rc::ptr_eq compares identity.
  • The entry API with or_insert_with makes the object only when the key is not in the map. A map of Weak pointers would let objects go when the program drops them, as the Python example does.

Consequences

Benefits.

  • No lost updates inside a session. All the code of a session changes the same object, so one save writes all the changes. The SQLAlchemy glossary says that with this pattern "all operations which occur for a particular database identity are transparently coordinated onto a single object instance."5 Entity Framework Core says that identity resolution "ensures Entity Framework Core (EF Core) is tracking a consistent graph with no ambiguities about the relationships or property values of the entities."6
  • Fewer queries. A lookup by key that hits the map costs no database call. Doctrine says that for a second find with the same id, "Doctrine will check the identity map first and doesn't need to make that database roundtrip."7
  • Object identity means row identity. Code can compare objects with the identity operator, and object graphs with cycles load correctly, because a reference to a row that is already loaded points to the existing object.
  • A base for change tracking. A Unit of Work can find all the objects of a session in the map. At the flush, Doctrine "will ask the identity map for all objects that are currently managed."7 See Unit of Work.

Liabilities.

Only lookups by key skip the query. The map knows objects only by key. "Doctrine only knows objects by id, so a query for different criteria has to go to the database, even if it was executed just before."7

Stale data. The map does not see changes that other sessions make to the database. SQLAlchemy designs for this case: "The design assumption here is to assume a transaction that's perfectly isolated", and the application refreshes objects when it needs to.3 A long session can show old values.

Memory. The map grows with each loaded object. Entity Framework Core gives this as the reason why no-tracking queries skip identity resolution: it "requires keeping track of each instance returned so that it can be used instead of later creating a duplicate."6 SQLAlchemy keeps the memory down with weak references: "Objects within the session are weakly referenced."8

A second object for a known key is an error. When the program makes its own object for a row that the session already holds, the map cannot hold both. Entity Framework Core throws an InvalidOperationException that says that "another instance with the key value '{Id: 1}' is already being tracked."6 SQLAlchemy and Doctrine also raise an error in this case.910

No map, two objects. Without an identity map, two reads of one row give two objects, and the last save wins.

This code runs but gives a wrong answer on purpose.

import sqlite3


class Person:
    def __init__(self, id, name, city):
        self.id, self.name, self.city = id, name, city


def find(db, id):  # bug: a new object for each call, so one row has two objects
    return Person(*db.execute("SELECT id, name, city FROM people WHERE id = ?", (id,)).fetchone())


def save(db, p):
    db.execute("UPDATE people SET name = ?, city = ? WHERE id = ?", (p.name, p.city, p.id))


db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT, city TEXT)")
db.execute("INSERT INTO people VALUES (1, 'Ann', 'Oslo')")

a = find(db, 1)  # one part of the program corrects the name
a.name = "Anna"
b = find(db, 1)  # another part moves the same person
b.city = "Rome"
save(db, a)
save(db, b)  # writes the old name back
print(db.execute("SELECT name, city FROM people WHERE id = 1").fetchone())
Output
('Ann', 'Rome')

The name change is lost. With the PersonMapper of the Solution section, a and b are the same object, and the row gets both changes: ('Anna', 'Rome').

When not to use it

For read-only data. A report that only reads rows and never changes them gains little from the map and pays for it in memory. Entity Framework Core says that no-tracking queries "are useful when the results are used in a read-only scenario."11

As a cache that many sessions share. The map belongs to one session and one business transaction. Shared between users or threads, it serves stale objects and needs locks. SQLAlchemy says that "a particular instance of Session should be used in only one thread or task at a time."3 A cache across sessions is a different design, with rules for expiry.

For immutable values. A value object that never changes, such as a currency, can be copied freely. Two copies cannot diverge, so the map adds nothing.

One map per class or per hierarchy. The map can be one dictionary for each table, or one dictionary keyed by the class and the key. Doctrine keys its map by "root entity name" and "id", so all the classes of one inheritance hierarchy share one map.710

Weak and strong maps. A strong map keeps every loaded object until the session ends. A weak map drops an object when the program no longer uses it. SQLAlchemy uses a weak map but keeps a strong reference to the objects that are new, deleted or changed, because their changes are not yet written.8

Identity resolution without tracking. Entity Framework Core can resolve identities within one query without tracking the objects, with AsNoTrackingWithIdentityResolution.11

Unit of Work. The map is usually part of the Unit of Work, which uses it to find changed objects. See Unit of Work.

Identity Field. The key of the map is the database key that the object stores. See Identity Field.

Lazy Load. A placeholder for an object that is not loaded yet must also go through the map, or a later load makes a second object. Doctrine returns the same reference for a proxy and for a later find of the same id.7 See Lazy Load.

Known uses

  • SQLAlchemy: the Session keeps its objects "inside a structure called the identity map", which holds "only one object with a particular primary key".3 The map is WeakInstanceDict in identity.py at 2.0.57. Its add method raises an error when "another instance with key %s is already present in this session."9
  • Doctrine ORM, for PHP: "Doctrine uses the Identity Map pattern to track objects."7 In UnitOfWork.php at 3.8.0, addToIdentityMap stores each entity under the root class name and a hash of its id, and throws an EntityIdentityCollisionException when another object has the same id.10
  • Entity Framework Core, for .NET: "A DbContext can only track one entity instance with any given primary key value."6 In a tracking query, "If EF Core finds an existing entity, then the same instance is returned".11

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Identity Map, pattern summary; the book's Chapter 11
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 11, Object-Relational Behavioral Patterns, Identity Map
  3. SQLAlchemy 2.0 documentation, Session Basics, What does the Session do; Get by Primary Key; Expiring / Refreshing; Is the Session thread-safe
  4. Doctrine ORM 3.7 documentation, Working with Objects, Entities and the Identity Map
  5. SQLAlchemy 2.0 documentation, Glossary, identity map
  6. Entity Framework Core documentation, Identity Resolution in EF Core, introduction; Identity resolution and queries
  7. Doctrine ORM 3.7 documentation, Doctrine Internals explained, How Doctrine keeps track of Objects
  8. SQLAlchemy 2.0 documentation, State Management, Session Referencing Behavior
  9. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/identity.py, class WeakInstanceDict, lines 126 to 291
  10. Doctrine ORM 3.8.0 source, src/UnitOfWork.php, UnitOfWork::addToIdentityMap, lines 1722 to 1739
  11. Entity Framework Core documentation, Tracking vs. No-Tracking Queries, Tracking queries; No-tracking queries; Identity resolution

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