Programming Search⌘K

Patternadvanced

Metadata Mapping

Also called metadata mapping pattern, mapping metadata, metadata-driven mapping.

Metadata Mapping holds the mapping between fields and columns as data, and generic code, by reflection or by generated code, reads it to load, insert and update objects.

Family
architectural
Intent
Holds details of object-relational mapping in metadata.

Intent

Metadata Mapping "Holds details of object-relational mapping in metadata."1 The program states once, as data, which class goes to which table and which field goes to which column. Generic code reads that data to load, insert and update objects of any mapped class.

Problem

Fowler describes the code that this pattern removes: "Much of the code that deals with object-relational mapping describes how fields in the database correspond to fields in in-memory objects. The resulting code tends to be tedious and repetitive to write."1 A hand-written mapper for each class repeats the same steps with different names: list the columns, list the values in the same order, read each column back into its field. With many classes, this code is large, and each copy is a place for a mistake.

Solution

"A Metadata Mapping allows developers to define the mappings in a simple tabular form, which can then be processed by generic code to carry out the details of reading, inserting, and updating the data."1

The participants are the data map for each class, which names the class and the table and holds a column map for each field; and the generic mapper, which builds the SQL and moves the values from the metadata. The metadata can be in the code, in a file, or in annotations on the class.

There are two ways for the generic code to get to the fields.2 A reflective program reads and writes the fields by name at run time, with the reflection of the language. Code generation reads the metadata before the program runs and writes ordinary mapper code for each class. Reflection is simpler to change; generated code is plain code that the compiler checks.

  metadata                                    generic mapper
  Player -> table player                      insert(obj): for each column map,
     id      -> id                                 column list  += column
     name    -> name                               value list   += field of obj
     country -> nation                        find(cls, id): for each column map,
  Club   -> table club                             field of new obj = column of row
     id -> id, name -> title, city -> city

The following program builds an insert statement and its values for a player from a data map, with no code that names the fields of Player.

class Player:
    def __init__(self, name, country):
        self.name, self.country = name, country


# The mapping is data: pairs of field and column. Generic code reads it.
PLAYER_MAP = ("player", [("name", "name"), ("country", "nation")])


def insert_sql(obj, data_map):
    table, columns = data_map
    cols = ", ".join(c for _, c in columns)
    marks = ", ".join("?" for _ in columns)
    return f"insert into {table} ({cols}) values ({marks})", [getattr(obj, f) for f, _ in columns]


print(insert_sql(Player("Ann", "NZ"), PLAYER_MAP))
Output
('insert into player (name, nation) values (?, ?)', ['Ann', 'NZ'])

Example

Each example file has two classes, Player and Club, and a data map for each. In both classes the field name maps to a different column: name in the player table and title in the club table. The field country maps to the column nation. The program prints the two maps, then inserts a player and a club, and prints the insert statement that the one generic mapper built for each. It finds both by key, changes the country of the player, prints the update statement, and prints the rows. The Python file runs the statements in SQLite. The other files keep the rows in maps and print the same statements. Python, JavaScript, Java and Go read and write the fields by name at run time. Rust has no run-time reflection, so a macro_rules! macro reads the metadata at compile time and generates the code for each struct, which is the code generation form of the pattern.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table player (id integer primary key, name text, nation text);
create table club (id integer primary key, title text, city text);
""")


class Player:
    def __init__(self, id=None, name=None, country=None):
        self.id, self.name, self.country = id, name, country

    def __repr__(self):
        return f"Player(id={self.id}, name={self.name}, country={self.country})"


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

    def __repr__(self):
        return f"Club(id={self.id}, name={self.name}, city={self.city})"


class DataMap:
    # The metadata: the class, the table and the pairs of field and column.
    def __init__(self, cls, table, columns):
        self.cls, self.table, self.columns = cls, table, columns

    def describe(self):
        pairs = ", ".join(f"{f} -> {c}" for f, c in self.columns)
        return f"{self.cls.__name__} -> table {self.table}: {pairs}"


MAPS = {
    Player: DataMap(Player, "player", [("id", "id"), ("name", "name"), ("country", "nation")]),
    Club: DataMap(Club, "club", [("id", "id"), ("name", "title"), ("city", "city")]),
}


class Mapper:
    # Generic code: it reads the metadata and uses reflection on the fields.
    def insert(self, obj):
        m = MAPS[type(obj)]
        cols = ", ".join(c for _, c in m.columns)
        marks = ", ".join("?" for _ in m.columns)
        sql = f"insert into {m.table} ({cols}) values ({marks})"
        db.execute(sql, [getattr(obj, f) for f, _ in m.columns])
        return sql

    def find(self, cls, id):
        m = MAPS[cls]
        sql = f"select {', '.join(c for _, c in m.columns)} from {m.table} where id = ?"
        row = db.execute(sql, (id,)).fetchone()
        obj = cls()
        for (f, _), value in zip(m.columns, row):
            setattr(obj, f, value)
        return obj

    def update(self, obj):
        m = MAPS[type(obj)]
        sets = ", ".join(f"{c} = ?" for f, c in m.columns if f != "id")
        sql = f"update {m.table} set {sets} where id = ?"
        db.execute(sql, [getattr(obj, f) for f, _ in m.columns if f != "id"] + [obj.id])
        return sql


mapper = Mapper()
for m in MAPS.values():
    print("map", m.describe())
print("insert:", mapper.insert(Player(1, "Ann", "NZ")))
print("insert:", mapper.insert(Club(1, "Lions", "Leeds")))
p = mapper.find(Player, 1)
print("find player 1:", p)
print("find club 1:", mapper.find(Club, 1))
p.country = "AU"
print("update:", mapper.update(p))
for table in ("player", "club"):
    for row in db.execute(f"select * from {table} order by id"):
        print(f"row in {table}:", " ".join(str(v) for v in row))
Output
map Player -> table player: id -> id, name -> name, country -> nation
map Club -> table club: id -> id, name -> title, city -> city
insert: insert into player (id, name, nation) values (?, ?, ?)
insert: insert into club (id, title, city) values (?, ?, ?)
find player 1: Player(id=1, name=Ann, country=NZ)
find club 1: Club(id=1, name=Lions, city=Leeds)
update: update player set name = ?, nation = ? where id = ?
row in player: 1 Ann AU
row in club: 1 Lions Leeds
  • Verdict: idiom. DataMap holds the class, the table and the pairs of field and column, and Mapper uses getattr and setattr to move each value. The SQL text comes from the metadata, and SQLite runs it.
  • SQLAlchemy and Django keep the same kind of metadata in a Mapper and in Model._meta, and build the SQL from it.
JavaGitHub
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    // A stand-in for the database: each table maps an id to a row of columns.
    static final Map<String, Map<Integer, Map<String, Object>>> DB = Map.of("player", new TreeMap<>(), "club", new TreeMap<>());

    public static class Player {
        public Integer id;
        public String name;
        public String country;

        public Player() {}

        Player(int id, String name, String country) {
            this.id = id;
            this.name = name;
            this.country = country;
        }

        @Override
        public String toString() {
            return "Player(id=" + id + ", name=" + name + ", country=" + country + ")";
        }
    }

    public static class Club {
        public Integer id;
        public String name;
        public String city;

        public Club() {}

        Club(int id, String name, String city) {
            this.id = id;
            this.name = name;
            this.city = city;
        }

        @Override
        public String toString() {
            return "Club(id=" + id + ", name=" + name + ", city=" + city + ")";
        }
    }

    record ColumnMap(String field, String column) {}

    // The metadata: the class, the table and the pairs of field and column.
    record DataMap(Class<?> cls, String table, List<ColumnMap> columns) {
        String describe() {
            List<String> pairs = new ArrayList<>();
            for (ColumnMap c : columns) pairs.add(c.field() + " -> " + c.column());
            return cls.getSimpleName() + " -> table " + table + ": " + String.join(", ", pairs);
        }
    }

    static final Map<Class<?>, DataMap> MAPS = new LinkedHashMap<>();

    static {
        MAPS.put(Player.class, new DataMap(Player.class, "player",
                List.of(new ColumnMap("id", "id"), new ColumnMap("name", "name"), new ColumnMap("country", "nation"))));
        MAPS.put(Club.class, new DataMap(Club.class, "club",
                List.of(new ColumnMap("id", "id"), new ColumnMap("name", "title"), new ColumnMap("city", "city"))));
    }

    // Generic code: it reads the metadata and uses reflection on the fields.
    static final class Mapper {
        static Object get(Object obj, String field) throws ReflectiveOperationException {
            Field f = obj.getClass().getField(field);
            return f.get(obj);
        }

        String insert(Object obj) throws ReflectiveOperationException {
            DataMap m = MAPS.get(obj.getClass());
            List<String> cols = new ArrayList<>();
            List<String> marks = new ArrayList<>();
            Map<String, Object> row = new LinkedHashMap<>();
            for (ColumnMap c : m.columns()) {
                cols.add(c.column());
                marks.add("?");
                row.put(c.column(), get(obj, c.field()));
            }
            DB.get(m.table()).put((Integer) get(obj, "id"), row);
            return "insert into " + m.table() + " (" + String.join(", ", cols) + ") values (" + String.join(", ", marks) + ")";
        }

        <T> T find(Class<T> cls, int id) throws ReflectiveOperationException {
            DataMap m = MAPS.get(cls);
            Map<String, Object> row = DB.get(m.table()).get(id);
            T obj = cls.getDeclaredConstructor().newInstance();
            for (ColumnMap c : m.columns()) {
                cls.getField(c.field()).set(obj, row.get(c.column()));
            }
            return obj;
        }

        String update(Object obj) throws ReflectiveOperationException {
            DataMap m = MAPS.get(obj.getClass());
            Map<String, Object> row = DB.get(m.table()).get((Integer) get(obj, "id"));
            List<String> sets = new ArrayList<>();
            for (ColumnMap c : m.columns()) {
                if (c.field().equals("id")) continue;
                row.put(c.column(), get(obj, c.field()));
                sets.add(c.column() + " = ?");
            }
            return "update " + m.table() + " set " + String.join(", ", sets) + " where id = ?";
        }
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        Mapper mapper = new Mapper();
        for (DataMap m : MAPS.values()) System.out.println("map " + m.describe());
        System.out.println("insert: " + mapper.insert(new Player(1, "Ann", "NZ")));
        System.out.println("insert: " + mapper.insert(new Club(1, "Lions", "Leeds")));
        Player p = mapper.find(Player.class, 1);
        System.out.println("find player 1: " + p);
        System.out.println("find club 1: " + mapper.find(Club.class, 1));
        p.country = "AU";
        System.out.println("update: " + mapper.update(p));
        for (String table : List.of("player", "club")) {
            for (Map<String, Object> row : DB.get(table).values()) {
                List<String> vs = new ArrayList<>();
                for (Object v : row.values()) vs.add(String.valueOf(v));
                System.out.println("row in " + table + ": " + String.join(" ", vs));
            }
        }
    }
}
Output
map Player -> table player: id -> id, name -> name, country -> nation
map Club -> table club: id -> id, name -> title, city -> city
insert: insert into player (id, name, nation) values (?, ?, ?)
insert: insert into club (id, title, city) values (?, ?, ?)
find player 1: Player(id=1, name=Ann, country=NZ)
find club 1: Club(id=1, name=Lions, city=Leeds)
update: update player set name = ?, nation = ? where id = ?
row in player: 1 Ann AU
row in club: 1 Lions Leeds
  • Verdict: idiom. Class.getField and Field.get and Field.set move the values, and getDeclaredConstructor().newInstance() creates the empty object. The mapped fields are public so that reflection can reach them without setAccessible.
  • Jakarta Persistence puts the same metadata in annotations, such as @Table and @Column, and the provider reads them with reflection.
JavaScriptGitHub
// A stand-in for the database: each table maps an id to a row of columns.
const db = { player: new Map(), club: new Map() };

class Player {
  constructor(id = null, name = null, country = null) {
    Object.assign(this, { id, name, country });
  }
  toString() {
    return `Player(id=${this.id}, name=${this.name}, country=${this.country})`;
  }
}

class Club {
  constructor(id = null, name = null, city = null) {
    Object.assign(this, { id, name, city });
  }
  toString() {
    return `Club(id=${this.id}, name=${this.name}, city=${this.city})`;
  }
}

// The metadata: the class, the table and the pairs of field and column.
class DataMap {
  constructor(cls, table, columns) {
    Object.assign(this, { cls, table, columns });
  }
  describe() {
    const pairs = this.columns.map(([f, c]) => `${f} -> ${c}`).join(", ");
    return `${this.cls.name} -> table ${this.table}: ${pairs}`;
  }
}

const MAPS = new Map([
  [Player, new DataMap(Player, "player", [["id", "id"], ["name", "name"], ["country", "nation"]])],
  [Club, new DataMap(Club, "club", [["id", "id"], ["name", "title"], ["city", "city"]])],
]);

// Generic code: it reads the metadata and reads and writes the fields by name.
class Mapper {
  insert(obj) {
    const m = MAPS.get(obj.constructor);
    const cols = m.columns.map(([, c]) => c).join(", ");
    const marks = m.columns.map(() => "?").join(", ");
    const row = new Map(m.columns.map(([f, c]) => [c, obj[f]]));
    db[m.table].set(obj.id, row);
    return `insert into ${m.table} (${cols}) values (${marks})`;
  }
  find(cls, id) {
    const m = MAPS.get(cls);
    const row = db[m.table].get(id);
    const obj = new cls();
    for (const [f, c] of m.columns) obj[f] = row.get(c);
    return obj;
  }
  update(obj) {
    const m = MAPS.get(obj.constructor);
    const rest = m.columns.filter(([f]) => f !== "id");
    const row = db[m.table].get(obj.id);
    for (const [f, c] of rest) row.set(c, obj[f]);
    return `update ${m.table} set ${rest.map(([, c]) => `${c} = ?`).join(", ")} where id = ?`;
  }
}

const mapper = new Mapper();
for (const m of MAPS.values()) console.log(`map ${m.describe()}`);
console.log(`insert: ${mapper.insert(new Player(1, "Ann", "NZ"))}`);
console.log(`insert: ${mapper.insert(new Club(1, "Lions", "Leeds"))}`);
const p = mapper.find(Player, 1);
console.log(`find player 1: ${p}`);
console.log(`find club 1: ${mapper.find(Club, 1)}`);
p.country = "AU";
console.log(`update: ${mapper.update(p)}`);
for (const table of ["player", "club"]) {
  for (const row of db[table].values()) console.log(`row in ${table}: ${[...row.values()].join(" ")}`);
}
Output
map Player -> table player: id -> id, name -> name, country -> nation
map Club -> table club: id -> id, name -> title, city -> city
insert: insert into player (id, name, nation) values (?, ?, ?)
insert: insert into club (id, title, city) values (?, ?, ?)
find player 1: Player(id=1, name=Ann, country=NZ)
find club 1: Club(id=1, name=Lions, city=Leeds)
update: update player set name = ?, nation = ? where id = ?
row in player: 1 Ann AU
row in club: 1 Lions Leeds
  • Verdict: idiom. Property access with obj[f] is the reflection of JavaScript, and new cls() creates an empty object of the mapped class. MAPS uses the class itself as the key.
  • The rows are kept in maps from column name to value, so the generic code also writes the columns by name.
package main

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

type row map[string]any

// A stand-in for the database: each table maps an id to a row of columns.
var db = map[string]map[int]row{"player": {}, "club": {}}

type Player struct {
	ID            int
	Name, Country string
}

func (p Player) String() string {
	return fmt.Sprintf("Player(id=%d, name=%s, country=%s)", p.ID, p.Name, p.Country)
}

type Club struct {
	ID         int
	Name, City string
}

func (c Club) String() string {
	return fmt.Sprintf("Club(id=%d, name=%s, city=%s)", c.ID, c.Name, c.City)
}

type columnMap struct{ Field, Column string }

// dataMap is the metadata: the type, the table and the pairs of field and column.
type dataMap struct {
	Type    reflect.Type
	Table   string
	Columns []columnMap
}

func (m dataMap) describe() string {
	var pairs []string
	for _, c := range m.Columns {
		// Go field names start with a capital letter; the output uses lower case.
		pairs = append(pairs, strings.ToLower(c.Field)+" -> "+c.Column)
	}
	return fmt.Sprintf("%s -> table %s: %s", m.Type.Name(), m.Table, strings.Join(pairs, ", "))
}

var maps = []dataMap{
	{reflect.TypeOf(Player{}), "player", []columnMap{{"ID", "id"}, {"Name", "name"}, {"Country", "nation"}}},
	{reflect.TypeOf(Club{}), "club", []columnMap{{"ID", "id"}, {"Name", "title"}, {"City", "city"}}},
}

func mapFor(t reflect.Type) dataMap {
	for _, m := range maps {
		if m.Type == t {
			return m
		}
	}
	panic("no data map for " + t.Name())
}

// insert, find and update are generic: they read the metadata and use reflection on the fields.
func insert(obj any) string {
	v := reflect.ValueOf(obj).Elem()
	m := mapFor(v.Type())
	var cols, marks []string
	r := row{}
	for _, c := range m.Columns {
		cols = append(cols, c.Column)
		marks = append(marks, "?")
		r[c.Column] = v.FieldByName(c.Field).Interface()
	}
	db[m.Table][v.FieldByName("ID").Interface().(int)] = r
	return fmt.Sprintf("insert into %s (%s) values (%s)", m.Table, strings.Join(cols, ", "), strings.Join(marks, ", "))
}

func find(obj any, id int) {
	v := reflect.ValueOf(obj).Elem()
	m := mapFor(v.Type())
	r := db[m.Table][id]
	for _, c := range m.Columns {
		v.FieldByName(c.Field).Set(reflect.ValueOf(r[c.Column]))
	}
}

func update(obj any) string {
	v := reflect.ValueOf(obj).Elem()
	m := mapFor(v.Type())
	r := db[m.Table][v.FieldByName("ID").Interface().(int)]
	var sets []string
	for _, c := range m.Columns {
		if c.Field == "ID" {
			continue
		}
		r[c.Column] = v.FieldByName(c.Field).Interface()
		sets = append(sets, c.Column+" = ?")
	}
	return fmt.Sprintf("update %s set %s where id = ?", m.Table, strings.Join(sets, ", "))
}

func main() {
	for _, m := range maps {
		fmt.Println("map", m.describe())
	}
	fmt.Println("insert:", insert(&Player{1, "Ann", "NZ"}))
	fmt.Println("insert:", insert(&Club{1, "Lions", "Leeds"}))
	var p Player
	find(&p, 1)
	fmt.Println("find player 1:", p)
	var c Club
	find(&c, 1)
	fmt.Println("find club 1:", c)
	p.Country = "AU"
	fmt.Println("update:", update(&p))
	for _, m := range maps {
		ids := make([]int, 0, len(db[m.Table]))
		for id := range db[m.Table] {
			ids = append(ids, id)
		}
		sort.Ints(ids)
		for _, id := range ids {
			var vs []string
			for _, c := range m.Columns {
				vs = append(vs, fmt.Sprint(db[m.Table][id][c.Column]))
			}
			fmt.Printf("row in %s: %s\n", m.Table, strings.Join(vs, " "))
		}
	}
}
Output
map Player -> table player: id -> id, name -> name, country -> nation
map Club -> table club: id -> id, name -> title, city -> city
insert: insert into player (id, name, nation) values (?, ?, ?)
insert: insert into club (id, title, city) values (?, ?, ?)
find player 1: Player(id=1, name=Ann, country=NZ)
find club 1: Club(id=1, name=Lions, city=Leeds)
update: update player set name = ?, nation = ? where id = ?
row in player: 1 Ann AU
row in club: 1 Lions Leeds
  • Verdict: idiom. The reflect package gives FieldByName, Interface and Set, and find takes a pointer so that it can set the fields. Go field names start with a capital letter, so describe prints them in lower case.
  • Many Go libraries keep this metadata in struct tags, such as db:"nation", and read the tags with reflect.
RustGitHub
use std::collections::BTreeMap;

#[derive(Clone, Debug)]
enum Value {
    Int(i64),
    Text(String),
}

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Value::Int(n) => write!(f, "{}", n),
            Value::Text(s) => write!(f, "{}", s),
        }
    }
}

impl From<&i64> for Value {
    fn from(n: &i64) -> Self {
        Value::Int(*n)
    }
}

impl From<&String> for Value {
    fn from(s: &String) -> Self {
        Value::Text(s.clone())
    }
}

trait FromValue {
    fn from_value(v: &Value) -> Self;
}

impl FromValue for i64 {
    fn from_value(v: &Value) -> Self {
        match v {
            Value::Int(n) => *n,
            Value::Text(_) => panic!("not an integer"),
        }
    }
}

impl FromValue for String {
    fn from_value(v: &Value) -> Self {
        match v {
            Value::Text(s) => s.clone(),
            Value::Int(_) => panic!("not text"),
        }
    }
}

// What the generic mapper needs from each mapped type.
trait Mapped: Sized {
    const NAME: &'static str;
    const TABLE: &'static str;
    const COLUMNS: &'static [(&'static str, &'static str)];
    fn id(&self) -> i64;
    fn values(&self) -> Vec<Value>;
    fn from_values(values: &[Value]) -> Self;
}

// Rust has no runtime reflection, so this macro reads the metadata at compile time
// and generates the struct and the code that moves each field to and from its column.
macro_rules! data_map {
    ($name:ident, $table:literal, { $($field:ident : $ty:ty => $column:literal),+ $(,)? }) => {
        #[derive(Debug)]
        struct $name {
            $($field: $ty),+
        }

        impl Mapped for $name {
            const NAME: &'static str = stringify!($name);
            const TABLE: &'static str = $table;
            const COLUMNS: &'static [(&'static str, &'static str)] = &[$((stringify!($field), $column)),+];
            fn id(&self) -> i64 {
                self.id
            }
            fn values(&self) -> Vec<Value> {
                vec![$(Value::from(&self.$field)),+]
            }
            fn from_values(values: &[Value]) -> Self {
                let mut it = values.iter();
                $name { $($field: <$ty>::from_value(it.next().expect("value"))),+ }
            }
        }
    };
}

data_map!(Player, "player", { id: i64 => "id", name: String => "name", country: String => "nation" });
data_map!(Club, "club", { id: i64 => "id", name: String => "title", city: String => "city" });

impl std::fmt::Display for Player {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "Player(id={}, name={}, country={})", self.id, self.name, self.country)
    }
}

impl std::fmt::Display for Club {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "Club(id={}, name={}, city={})", self.id, self.name, self.city)
    }
}

fn describe<T: Mapped>() -> String {
    let pairs: Vec<String> = T::COLUMNS.iter().map(|(f, c)| format!("{} -> {}", f, c)).collect();
    format!("{} -> table {}: {}", T::NAME, T::TABLE, pairs.join(", "))
}

// A stand-in for the database: each table maps an id to the values of its columns.
struct Mapper {
    db: BTreeMap<&'static str, BTreeMap<i64, Vec<Value>>>,
}

impl Mapper {
    fn insert<T: Mapped>(&mut self, obj: &T) -> String {
        self.db.entry(T::TABLE).or_default().insert(obj.id(), obj.values());
        let cols: Vec<&str> = T::COLUMNS.iter().map(|(_, c)| *c).collect();
        let marks = vec!["?"; T::COLUMNS.len()];
        format!("insert into {} ({}) values ({})", T::TABLE, cols.join(", "), marks.join(", "))
    }

    fn find<T: Mapped>(&self, id: i64) -> T {
        T::from_values(&self.db[T::TABLE][&id])
    }

    fn update<T: Mapped>(&mut self, obj: &T) -> String {
        self.db.get_mut(T::TABLE).expect("table").insert(obj.id(), obj.values());
        let sets: Vec<String> = T::COLUMNS.iter().filter(|(f, _)| *f != "id").map(|(_, c)| format!("{} = ?", c)).collect();
        format!("update {} set {} where id = ?", T::TABLE, sets.join(", "))
    }
}

fn main() {
    let mut mapper = Mapper { db: BTreeMap::new() };
    println!("map {}", describe::<Player>());
    println!("map {}", describe::<Club>());
    println!("insert: {}", mapper.insert(&Player { id: 1, name: "Ann".into(), country: "NZ".into() }));
    println!("insert: {}", mapper.insert(&Club { id: 1, name: "Lions".into(), city: "Leeds".into() }));
    let mut p: Player = mapper.find(1);
    println!("find player 1: {}", p);
    let c: Club = mapper.find(1);
    println!("find club 1: {}", c);
    p.country = "AU".into();
    println!("update: {}", mapper.update(&p));
    for table in ["player", "club"] {
        for values in mapper.db[table].values() {
            let vs: Vec<String> = values.iter().map(|v| v.to_string()).collect();
            println!("row in {}: {}", table, vs.join(" "));
        }
    }
}
Output
map Player -> table player: id -> id, name -> name, country -> nation
map Club -> table club: id -> id, name -> title, city -> city
insert: insert into player (id, name, nation) values (?, ?, ?)
insert: insert into club (id, title, city) values (?, ?, ?)
find player 1: Player(id=1, name=Ann, country=NZ)
find club 1: Club(id=1, name=Lions, city=Leeds)
update: update player set name = ?, nation = ? where id = ?
row in player: 1 Ann AU
row in club: 1 Lions Leeds
  • Verdict: idiom. Rust has no run-time reflection, so the data_map! macro reads the metadata at compile time and generates each struct with its Mapped impl: the table, the column list, values and from_values. This is the code generation form of the pattern.
  • The generic mapper uses the Mapped trait, so find::<Player> and find::<Club> share one implementation.

Consequences

Benefits.

  • Less code. One generic mapper serves all the classes, and a new class needs a new data map and no new mapper.
  • The mapping is in one place. A change of a column name is a change to one line of metadata.
  • The column list and the values come from the same data. They cannot be in a different order.
  • Other tools can read the metadata. The same maps can create the tables, check the schema or build forms.

Liabilities.

Hand-written mapping code is easy to get wrong. This is the problem the pattern solves. In the following program, the column list and the list of values are written separately, in a different order, so the name and the country of the player change places.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("create table player (id integer primary key, name text, nation text)")


class Player:
    def __init__(self, id, name, country):
        self.id, self.name, self.country = id, name, country


# Wrong: hand-written mapping code for each class. The column list and the
# list of values are written separately, and here they are in a different order.
def insert_player(p):
    db.execute("insert into player (id, name, nation) values (?, ?, ?)", (p.id, p.country, p.name))


insert_player(Player(1, "Ann", "NZ"))
print(db.execute("select name, nation from player").fetchall())
Output
[('NZ', 'Ann')]

The generic code is harder to read and to debug. The SQL does not appear in the source, and a mistake in the metadata shows only at run time when reflection is used.

Reflection has a cost and needs access. It is slower than direct field access, and it needs fields that the mapper can reach. In Java, the example uses public fields for this reason. Code generation removes the cost but adds a build step.

Special cases still need code. A field that maps to two columns, or a value that needs a conversion, needs more metadata or a hook in the generic mapper.

When not to use it

When there are few classes. For two or three tables, a hand-written Data Mapper is short and clear.

When an ORM already holds the metadata. SQLAlchemy, Django, Hibernate and Entity Framework Core use this pattern inside, so the program writes the metadata in their form and not a generic mapper of its own.

Where the metadata lives. It can be a table of data in the code, as in the examples; class attributes, as in Django models; annotations, as in Jakarta Persistence; or a separate mapping file.

Metadata from names. A mapper can derive most of the metadata from the names of the fields, and keep explicit metadata only for the differences. Hibernate does this with naming strategies: "When an entity does not explicitly name the database table that it maps to, we need to implicitly determine that table name."3

Related patterns. The metadata is read with Runtime reflection, or written as Annotations, or turned into code with Syntactic macros or a code generator. A generic Data Mapper is the usual reader of the metadata. Fowler's Query Object uses the same metadata to turn a query on fields into SQL on columns.2

Known uses

  • SQLAlchemy: the declarative and imperative mapping styles both produce a Mapper that holds the metadata. "The Declarative Mapping is the typical way that mappings are constructed in modern SQLAlchemy."4 _collect_insert_commands in persistence.py at 2.0.57 builds the parameters of an INSERT from the map mapper._propkey_to_col[table], from each attribute key to its column.5
  • Django: "The model _meta API is at the core of the Django ORM. It enables other parts of the system such as lookups, queries, forms, and the admin to understand the capabilities of each model."6 Model._save_table in base.py at 5.2.8 reads cls._meta and its local_concrete_fields to choose the fields to save.7
  • Hibernate and Jakarta Persistence: annotations such as @Entity, @Table and @Column, or a mapping file, hold the metadata, and a naming strategy fills in the names that the mapping does not give.3

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Metadata Mapping, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 13, Object-Relational Metadata Mapping Patterns, Metadata Mapping
  3. Hibernate ORM 6.6 User Guide, 3.5. Naming strategies; 3.5.1. ImplicitNamingStrategy
  4. SQLAlchemy 2.0 documentation, ORM Mapped Class Overview, ORM Mapping Styles; Declarative Mapping; Imperative Mapping
  5. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/persistence.py, _collect_insert_commands, lines 327 to 359
  6. Django 5.2 documentation, Model _meta API, class Options
  7. Django 5.2.8 source, django/db/models/base.py, Model._save_table, lines 1081 to 1099

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