Programming Search⌘K

Patternadvanced

Inheritance Mappers

Also called inheritance mappers pattern, mapper hierarchy.

Inheritance Mappers organizes the mappers of a class hierarchy: one mapper for each class maps the fields that the class declares, and one mapper for the hierarchy chooses the concrete mapper.

Family
architectural
Intent
A structure to organize database mappers that handle inheritance hierarchies.

Intent

Inheritance Mappers is "A structure to organize database mappers that handle inheritance hierarchies."1 Each mapper maps the fields that its class declares and uses the mapper of the superclass for the rest, and one mapper for the whole hierarchy chooses the right concrete mapper for each object and each row.

Problem

Fowler states the two needs: "When you map from an object-oriented inheritance hierarchy in memory to a relational database you have to minimize the amount of code needed to save and load the data to the database. You also want to provide both abstract and concrete mapping behavior that allows you to save or load a superclass or a subclass."1 With Footballer, Cricketer and Bowler under Player, the code for the fields of Player must not be copied into three mappers. And a program that asks for "player 3" does not know which class player 3 has, so some mapper must find out and load the right class.

Solution

Make a hierarchy of mapper classes that follows the hierarchy of domain classes, and add one mapper for the hierarchy as a whole.2

  • An abstract mapper for the root class, such as AbstractPlayerMapper, saves and loads the fields of Player, and holds the steps of insert and find that do not depend on the class.
  • A concrete mapper for each concrete class, such as FootballerMapper, saves and loads the fields that its class declares, and calls the mapper of the superclass first. BowlerMapper is a subclass of CricketerMapper, as Bowler is a subclass of Cricketer. Each concrete mapper knows how to create an empty object of its class.
  • A hierarchy mapper, such as PlayerMapper, is what the rest of the program uses. On insert, it chooses the concrete mapper from the class of the object. On find, it reads the type of the row and delegates to the concrete mapper for that type.

The mapper classes call each other like the template method pattern: the abstract mapper has the steps, and the subclasses fill in the fields. The same structure works for each of the three table designs; Fowler says that "the general structure works the same for all of them."1 Only the code that reads and writes the rows changes.

  domain classes            mapper classes
  Player                    AbstractPlayerMapper    name; the steps of insert and find
   |- Footballer             |- FootballerMapper    club, then calls AbstractPlayerMapper
   |- Cricketer              |- CricketerMapper     runs, then calls AbstractPlayerMapper
       |- Bowler                 |- BowlerMapper    wickets, then calls CricketerMapper
                            PlayerMapper            chooses a concrete mapper by class or by type

The following program saves a footballer through the hierarchy mapper. The mapper for the fields of Player writes the name, and the concrete mapper adds the type and the club.

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


class Footballer(Player):
    def __init__(self, name, club):
        super().__init__(name)
        self.club = club


class PlayerFieldsMapper:
    def save(self, p, row):
        row["name"] = p.name  # The fields of Player are mapped in one place.


class FootballerMapper(PlayerFieldsMapper):
    def save(self, p, row):
        super().save(p, row)
        row["type"], row["club"] = "footballer", p.club


class PlayerMapper:
    mappers = {Footballer: FootballerMapper()}

    def save(self, p):
        row = {}
        self.mappers[type(p)].save(p, row)  # Choose the concrete mapper and delegate.
        return row


print(PlayerMapper().save(Footballer("Ann", "Lions")))
Output
{'name': 'Ann', 'type': 'footballer', 'club': 'Lions'}

Example

Each example file stores the players in one table with a type column, as in Single Table Inheritance, and has the five mapper classes. It first prints the chain of mapper classes for each type: BowlerMapper, CricketerMapper and then AbstractPlayerMapper. It inserts a footballer, a cricketer and a bowler through PlayerMapper, and each insert prints which mapper wrote which field. For the bowler, three mapper classes write one row. Then it finds player 3 without knowing its class: PlayerMapper reads the type bowler from the row and uses BowlerMapper. The last line loads all the players, each with its own mapper. Python, JavaScript and Java use class inheritance for the mappers. Go and Rust have no class inheritance, so each mapper holds the mapper of its superclass and calls it.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row
db.execute("""create table player (id integer primary key, type text not null, name text not null,
              club text, runs integer, wickets integer)""")


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


class Footballer(Player):
    def __init__(self, name, club):
        super().__init__(name)
        self.club = club

    def describe(self):
        return f"Footballer {self.name}, club {self.club}"


class Cricketer(Player):
    def __init__(self, name, runs):
        super().__init__(name)
        self.runs = runs

    def describe(self):
        return f"Cricketer {self.name}, runs {self.runs}"


class Bowler(Cricketer):
    def __init__(self, name, runs, wickets):
        super().__init__(name, runs)
        self.wickets = wickets

    def describe(self):
        return f"Bowler {self.name}, runs {self.runs}, wickets {self.wickets}"


class AbstractPlayerMapper:
    # Each mapper class saves and loads the fields that its domain class declares,
    # and calls the mapper of the superclass for the inherited fields.
    def save(self, p, row, log):
        row["name"] = p.name
        log.append("name (Player)")

    def load(self, p, row):
        p.name = row["name"]

    def insert(self, p):
        row, log = {"type": self.type_code}, []
        self.save(p, row, log)
        cur = db.execute(f"insert into player ({', '.join(row)}) values ({', '.join('?' * len(row))})",
                         tuple(row.values()))
        p.id = cur.lastrowid
        return log

    def find(self, row):
        p = self.create()
        p.id = row["id"]
        self.load(p, row)
        return p


class FootballerMapper(AbstractPlayerMapper):
    type_code = "footballer"

    def create(self):
        return Footballer(None, None)

    def save(self, p, row, log):
        super().save(p, row, log)
        row["club"] = p.club
        log.append("club (Footballer)")

    def load(self, p, row):
        super().load(p, row)
        p.club = row["club"]


class CricketerMapper(AbstractPlayerMapper):
    type_code = "cricketer"

    def create(self):
        return Cricketer(None, None)

    def save(self, p, row, log):
        super().save(p, row, log)
        row["runs"] = p.runs
        log.append("runs (Cricketer)")

    def load(self, p, row):
        super().load(p, row)
        p.runs = row["runs"]


class BowlerMapper(CricketerMapper):
    type_code = "bowler"

    def create(self):
        return Bowler(None, None, None)

    def save(self, p, row, log):
        super().save(p, row, log)
        row["wickets"] = p.wickets
        log.append("wickets (Bowler)")

    def load(self, p, row):
        super().load(p, row)
        p.wickets = row["wickets"]


class PlayerMapper:
    # The mapper for the whole hierarchy: it chooses the concrete mapper and delegates to it.
    def __init__(self):
        self.by_type = {m.type_code: m for m in (FootballerMapper(), CricketerMapper(), BowlerMapper())}
        self.by_class = {Footballer: self.by_type["footballer"], Cricketer: self.by_type["cricketer"],
                         Bowler: self.by_type["bowler"]}

    def insert(self, p):
        mapper = self.by_class[type(p)]
        return mapper, mapper.insert(p)

    def find(self, id):
        row = db.execute("select * from player where id = ?", (id,)).fetchone()
        mapper = self.by_type[row["type"]]
        return mapper, mapper.find(row)

    def find_all(self):
        rows = db.execute("select * from player order by id").fetchall()
        return [self.by_type[row["type"]].find(row) for row in rows]


players = PlayerMapper()
for t, m in players.by_type.items():
    print(f"mapper chain for {t}: {', '.join(c.__name__ for c in type(m).__mro__[:-1])}")
for p in (Footballer("Ann", "Lions"), Cricketer("Bo", 412), Bowler("Cy", 95, 31)):
    mapper, log = players.insert(p)
    print(f"insert {p.name}: {type(mapper).__name__} saved {', '.join(log)}")
mapper, p = players.find(3)
print(f"find 3: {p.describe()} (mapper {type(mapper).__name__})")
print("find all:", " | ".join(p.describe() for p in players.find_all()))
Output
mapper chain for footballer: FootballerMapper, AbstractPlayerMapper
mapper chain for cricketer: CricketerMapper, AbstractPlayerMapper
mapper chain for bowler: BowlerMapper, CricketerMapper, AbstractPlayerMapper
insert Ann: FootballerMapper saved name (Player), club (Footballer)
insert Bo: CricketerMapper saved name (Player), runs (Cricketer)
insert Cy: BowlerMapper saved name (Player), runs (Cricketer), wickets (Bowler)
find 3: Bowler Cy, runs 95, wickets 31 (mapper BowlerMapper)
find all: Footballer Ann, club Lions | Cricketer Bo, runs 412 | Bowler Cy, runs 95, wickets 31
  • Verdict: idiom. Each mapper class overrides save and load and calls super() first, so the fields of each class are mapped once. AbstractPlayerMapper holds insert and find, and each concrete mapper gives type_code and create.
  • PlayerMapper keeps two maps, from type code and from class to the concrete mapper. __mro__ gives the chain of mapper classes that the first lines print.
JavaGitHub
import java.util.ArrayList;
import java.util.HashMap;
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: one player table with a type column.
    static final Map<Long, Map<String, Object>> PLAYER = new TreeMap<>();
    static long nextId = 1;

    abstract static class Player {
        Long id;
        String name;

        abstract String describe();
    }

    static class Footballer extends Player {
        String club;

        String describe() {
            return "Footballer " + name + ", club " + club;
        }
    }

    static class Cricketer extends Player {
        int runs;

        String describe() {
            return "Cricketer " + name + ", runs " + runs;
        }
    }

    static class Bowler extends Cricketer {
        int wickets;

        @Override
        String describe() {
            return "Bowler " + name + ", runs " + runs + ", wickets " + wickets;
        }
    }

    // Each mapper class saves and loads the fields that its domain class declares,
    // and calls the mapper of the superclass for the inherited fields.
    abstract static class AbstractPlayerMapper {
        abstract String typeCode();

        abstract Player create();

        void save(Player p, Map<String, Object> row, List<String> log) {
            row.put("name", p.name);
            log.add("name (Player)");
        }

        void load(Player p, Map<String, Object> row) {
            p.name = (String) row.get("name");
        }

        List<String> insert(Player p) {
            Map<String, Object> row = new HashMap<>();
            row.put("type", typeCode());
            List<String> log = new ArrayList<>();
            save(p, row, log);
            p.id = nextId++;
            PLAYER.put(p.id, row);
            return log;
        }

        Player find(long id, Map<String, Object> row) {
            Player p = create();
            p.id = id;
            load(p, row);
            return p;
        }
    }

    static class FootballerMapper extends AbstractPlayerMapper {
        String typeCode() {
            return "footballer";
        }

        Player create() {
            return new Footballer();
        }

        @Override
        void save(Player p, Map<String, Object> row, List<String> log) {
            super.save(p, row, log);
            row.put("club", ((Footballer) p).club);
            log.add("club (Footballer)");
        }

        @Override
        void load(Player p, Map<String, Object> row) {
            super.load(p, row);
            ((Footballer) p).club = (String) row.get("club");
        }
    }

    static class CricketerMapper extends AbstractPlayerMapper {
        String typeCode() {
            return "cricketer";
        }

        Player create() {
            return new Cricketer();
        }

        @Override
        void save(Player p, Map<String, Object> row, List<String> log) {
            super.save(p, row, log);
            row.put("runs", ((Cricketer) p).runs);
            log.add("runs (Cricketer)");
        }

        @Override
        void load(Player p, Map<String, Object> row) {
            super.load(p, row);
            ((Cricketer) p).runs = (Integer) row.get("runs");
        }
    }

    static class BowlerMapper extends CricketerMapper {
        @Override
        String typeCode() {
            return "bowler";
        }

        @Override
        Player create() {
            return new Bowler();
        }

        @Override
        void save(Player p, Map<String, Object> row, List<String> log) {
            super.save(p, row, log);
            row.put("wickets", ((Bowler) p).wickets);
            log.add("wickets (Bowler)");
        }

        @Override
        void load(Player p, Map<String, Object> row) {
            super.load(p, row);
            ((Bowler) p).wickets = (Integer) row.get("wickets");
        }
    }

    record Saved(AbstractPlayerMapper mapper, List<String> log) {}

    record Found(AbstractPlayerMapper mapper, Player player) {}

    // The mapper for the whole hierarchy: it chooses the concrete mapper and delegates to it.
    static class PlayerMapper {
        final Map<String, AbstractPlayerMapper> byType = new LinkedHashMap<>();
        final Map<Class<?>, AbstractPlayerMapper> byClass = new HashMap<>();

        PlayerMapper() {
            for (AbstractPlayerMapper m : List.of(new FootballerMapper(), new CricketerMapper(), new BowlerMapper())) {
                byType.put(m.typeCode(), m);
            }
            byClass.put(Footballer.class, byType.get("footballer"));
            byClass.put(Cricketer.class, byType.get("cricketer"));
            byClass.put(Bowler.class, byType.get("bowler"));
        }

        Saved insert(Player p) {
            AbstractPlayerMapper m = byClass.get(p.getClass());
            return new Saved(m, m.insert(p));
        }

        Found find(long id) {
            Map<String, Object> row = PLAYER.get(id);
            AbstractPlayerMapper m = byType.get((String) row.get("type"));
            return new Found(m, m.find(id, row));
        }

        List<Player> findAll() {
            List<Player> out = new ArrayList<>();
            PLAYER.forEach((id, row) -> out.add(byType.get((String) row.get("type")).find(id, row)));
            return out;
        }
    }

    static String chain(Object mapper) {
        List<String> names = new ArrayList<>();
        for (Class<?> c = mapper.getClass(); c != Object.class; c = c.getSuperclass()) {
            names.add(c.getSimpleName());
        }
        return String.join(", ", names);
    }


    public static void main(String[] args) {
        PlayerMapper players = new PlayerMapper();
        players.byType.forEach((t, m) -> System.out.println("mapper chain for " + t + ": " + chain(m)));
        Footballer ann = new Footballer();
        ann.name = "Ann";
        ann.club = "Lions";
        Cricketer bo = new Cricketer();
        bo.name = "Bo";
        bo.runs = 412;
        Bowler cy = new Bowler();
        cy.name = "Cy";
        cy.runs = 95;
        cy.wickets = 31;
        for (Player p : List.of(ann, bo, cy)) {
            Saved s = players.insert(p);
            System.out.println("insert " + p.name + ": " + s.mapper().getClass().getSimpleName() + " saved " + String.join(", ", s.log()));
        }
        Found f = players.find(3);
        System.out.println("find 3: " + f.player().describe() + " (mapper " + f.mapper().getClass().getSimpleName() + ")");
        List<String> all = new ArrayList<>();
        for (Player p : players.findAll()) {
            all.add(p.describe());
        }
        System.out.println("find all: " + String.join(" | ", all));
    }
}
Output
mapper chain for footballer: FootballerMapper, AbstractPlayerMapper
mapper chain for cricketer: CricketerMapper, AbstractPlayerMapper
mapper chain for bowler: BowlerMapper, CricketerMapper, AbstractPlayerMapper
insert Ann: FootballerMapper saved name (Player), club (Footballer)
insert Bo: CricketerMapper saved name (Player), runs (Cricketer)
insert Cy: BowlerMapper saved name (Player), runs (Cricketer), wickets (Bowler)
find 3: Bowler Cy, runs 95, wickets 31 (mapper BowlerMapper)
find all: Footballer Ann, club Lions | Cricketer Bo, runs 412 | Bowler Cy, runs 95, wickets 31
  • Verdict: idiom. AbstractPlayerMapper is an abstract class with the steps of insert and find, and each concrete mapper overrides save and load and calls super first. A row is a Map<String, Object>, so each mapper casts its own fields.
  • PlayerMapper maps p.getClass() to the concrete mapper. In Hibernate, the persister classes of the three table designs extend AbstractEntityPersister in the same way.
JavaScriptGitHub
// A stand-in for the database: one player table with a type column.
const playerTable = new Map();
let nextId = 1;

class Player {
  constructor(name) {
    this.id = null;
    this.name = name;
  }
}

class Footballer extends Player {
  constructor(name, club) {
    super(name);
    this.club = club;
  }
  describe() {
    return `Footballer ${this.name}, club ${this.club}`;
  }
}

class Cricketer extends Player {
  constructor(name, runs) {
    super(name);
    this.runs = runs;
  }
  describe() {
    return `Cricketer ${this.name}, runs ${this.runs}`;
  }
}

class Bowler extends Cricketer {
  constructor(name, runs, wickets) {
    super(name, runs);
    this.wickets = wickets;
  }
  describe() {
    return `Bowler ${this.name}, runs ${this.runs}, wickets ${this.wickets}`;
  }
}

// Each mapper class saves and loads the fields that its domain class declares,
// and calls the mapper of the superclass for the inherited fields.
class AbstractPlayerMapper {
  save(p, row, log) {
    row.name = p.name;
    log.push("name (Player)");
  }
  load(p, row) {
    p.name = row.name;
  }
  insert(p) {
    const row = { type: this.constructor.typeCode };
    const log = [];
    this.save(p, row, log);
    p.id = nextId++;
    playerTable.set(p.id, row);
    return log;
  }
  find(id, row) {
    const p = this.create();
    p.id = id;
    this.load(p, row);
    return p;
  }
}

class FootballerMapper extends AbstractPlayerMapper {
  static typeCode = "footballer";
  create() {
    return new Footballer(null, null);
  }
  save(p, row, log) {
    super.save(p, row, log);
    row.club = p.club;
    log.push("club (Footballer)");
  }
  load(p, row) {
    super.load(p, row);
    p.club = row.club;
  }
}

class CricketerMapper extends AbstractPlayerMapper {
  static typeCode = "cricketer";
  create() {
    return new Cricketer(null, null);
  }
  save(p, row, log) {
    super.save(p, row, log);
    row.runs = p.runs;
    log.push("runs (Cricketer)");
  }
  load(p, row) {
    super.load(p, row);
    p.runs = row.runs;
  }
}

class BowlerMapper extends CricketerMapper {
  static typeCode = "bowler";
  create() {
    return new Bowler(null, null, null);
  }
  save(p, row, log) {
    super.save(p, row, log);
    row.wickets = p.wickets;
    log.push("wickets (Bowler)");
  }
  load(p, row) {
    super.load(p, row);
    p.wickets = row.wickets;
  }
}

// The mapper for the whole hierarchy: it chooses the concrete mapper and delegates to it.
class PlayerMapper {
  constructor() {
    this.byType = new Map([new FootballerMapper(), new CricketerMapper(), new BowlerMapper()].map((m) => [m.constructor.typeCode, m]));
    this.byClass = new Map([
      [Footballer, this.byType.get("footballer")],
      [Cricketer, this.byType.get("cricketer")],
      [Bowler, this.byType.get("bowler")],
    ]);
  }
  insert(p) {
    const mapper = this.byClass.get(p.constructor);
    return [mapper, mapper.insert(p)];
  }
  find(id) {
    const row = playerTable.get(id);
    const mapper = this.byType.get(row.type);
    return [mapper, mapper.find(id, row)];
  }
  findAll() {
    return [...playerTable].map(([id, row]) => this.byType.get(row.type).find(id, row));
  }
}

function chain(mapper) {
  const names = [];
  for (let c = mapper.constructor; c !== Function.prototype && c.name; c = Object.getPrototypeOf(c)) names.push(c.name);
  return names.join(", ");
}

const players = new PlayerMapper();
for (const [t, m] of players.byType) console.log(`mapper chain for ${t}: ${chain(m)}`);
for (const p of [new Footballer("Ann", "Lions"), new Cricketer("Bo", 412), new Bowler("Cy", 95, 31)]) {
  const [mapper, log] = players.insert(p);
  console.log(`insert ${p.name}: ${mapper.constructor.name} saved ${log.join(", ")}`);
}
const [mapper, p] = players.find(3);
console.log(`find 3: ${p.describe()} (mapper ${mapper.constructor.name})`);
console.log(`find all: ${players.findAll().map((q) => q.describe()).join(" | ")}`);
Output
mapper chain for footballer: FootballerMapper, AbstractPlayerMapper
mapper chain for cricketer: CricketerMapper, AbstractPlayerMapper
mapper chain for bowler: BowlerMapper, CricketerMapper, AbstractPlayerMapper
insert Ann: FootballerMapper saved name (Player), club (Footballer)
insert Bo: CricketerMapper saved name (Player), runs (Cricketer)
insert Cy: BowlerMapper saved name (Player), runs (Cricketer), wickets (Bowler)
find 3: Bowler Cy, runs 95, wickets 31 (mapper BowlerMapper)
find all: Footballer Ann, club Lions | Cricketer Bo, runs 412 | Bowler Cy, runs 95, wickets 31
  • Verdict: idiom. The mapper classes use extends and super.save, as the domain classes do. Each concrete mapper has a static typeCode, and PlayerMapper finds the mapper for an object from p.constructor.
  • chain walks the prototype chain of the mapper class with Object.getPrototypeOf.
package main

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

type row map[string]any

// A stand-in for the database: one player table with a type column.
var (
	playerTable       = map[int64]row{}
	nextID      int64 = 1
)

// PlayerBase holds the fields of Player. Go has no class inheritance, so the
// domain types embed it, and Bowler embeds Cricketer.
type PlayerBase struct {
	ID   int64
	Name string
}

func (p *PlayerBase) base() *PlayerBase { return p }

type Player interface {
	base() *PlayerBase
	Describe() string
}

type Footballer struct {
	PlayerBase
	Club string
}

type Cricketer struct {
	PlayerBase
	Runs int
}

type Bowler struct {
	Cricketer
	Wickets int
}

func (f *Footballer) Describe() string { return fmt.Sprintf("Footballer %s, club %s", f.Name, f.Club) }
func (c *Cricketer) Describe() string  { return fmt.Sprintf("Cricketer %s, runs %d", c.Name, c.Runs) }
func (b *Bowler) Describe() string {
	return fmt.Sprintf("Bowler %s, runs %d, wickets %d", b.Name, b.Runs, b.Wickets)
}

// concreteMapper is what the generic insert and find need from each mapper.
type concreteMapper interface {
	typeCode() string
	name() string
	chain() []string
	create() Player
	save(p Player, r row, log *[]string)
	load(p Player, r row)
}

// AbstractPlayerMapper maps the fields of Player. Each mapper embeds the mapper
// of its superclass and calls it for the inherited fields.
type AbstractPlayerMapper struct{}

func (AbstractPlayerMapper) chain() []string { return []string{"AbstractPlayerMapper"} }
func (AbstractPlayerMapper) save(p Player, r row, log *[]string) {
	r["name"] = p.base().Name
	*log = append(*log, "name (Player)")
}
func (AbstractPlayerMapper) load(p Player, r row) { p.base().Name = r["name"].(string) }

type FootballerMapper struct{ AbstractPlayerMapper }

func (FootballerMapper) typeCode() string { return "footballer" }
func (FootballerMapper) name() string     { return "FootballerMapper" }
func (m FootballerMapper) chain() []string {
	return append([]string{m.name()}, m.AbstractPlayerMapper.chain()...)
}
func (FootballerMapper) create() Player { return &Footballer{} }
func (m FootballerMapper) save(p Player, r row, log *[]string) {
	m.AbstractPlayerMapper.save(p, r, log)
	r["club"] = p.(*Footballer).Club
	*log = append(*log, "club (Footballer)")
}
func (m FootballerMapper) load(p Player, r row) {
	m.AbstractPlayerMapper.load(p, r)
	p.(*Footballer).Club = r["club"].(string)
}

type CricketerMapper struct{ AbstractPlayerMapper }

func (CricketerMapper) typeCode() string { return "cricketer" }
func (CricketerMapper) name() string     { return "CricketerMapper" }
func (m CricketerMapper) chain() []string {
	return append([]string{m.name()}, m.AbstractPlayerMapper.chain()...)
}
func (CricketerMapper) create() Player { return &Cricketer{} }

// cricketer gives the Cricketer part of a Cricketer or a Bowler.
func cricketer(p Player) *Cricketer {
	if b, ok := p.(*Bowler); ok {
		return &b.Cricketer
	}
	return p.(*Cricketer)
}
func (m CricketerMapper) save(p Player, r row, log *[]string) {
	m.AbstractPlayerMapper.save(p, r, log)
	r["runs"] = cricketer(p).Runs
	*log = append(*log, "runs (Cricketer)")
}
func (m CricketerMapper) load(p Player, r row) {
	m.AbstractPlayerMapper.load(p, r)
	cricketer(p).Runs = r["runs"].(int)
}

type BowlerMapper struct{ CricketerMapper }

func (BowlerMapper) typeCode() string { return "bowler" }
func (BowlerMapper) name() string     { return "BowlerMapper" }
func (m BowlerMapper) chain() []string {
	return append([]string{m.name()}, m.CricketerMapper.chain()...)
}
func (BowlerMapper) create() Player { return &Bowler{} }
func (m BowlerMapper) save(p Player, r row, log *[]string) {
	m.CricketerMapper.save(p, r, log)
	r["wickets"] = p.(*Bowler).Wickets
	*log = append(*log, "wickets (Bowler)")
}
func (m BowlerMapper) load(p Player, r row) {
	m.CricketerMapper.load(p, r)
	p.(*Bowler).Wickets = r["wickets"].(int)
}

func insert(m concreteMapper, p Player) []string {
	r := row{"type": m.typeCode()}
	var log []string
	m.save(p, r, &log)
	p.base().ID = nextID
	playerTable[nextID] = r
	nextID++
	return log
}

func find(m concreteMapper, id int64, r row) Player {
	p := m.create()
	p.base().ID = id
	m.load(p, r)
	return p
}

// PlayerMapper is the mapper for the whole hierarchy: it chooses the concrete
// mapper and delegates to it.
type PlayerMapper struct {
	order  []string
	byType map[string]concreteMapper
}

func newPlayerMapper() *PlayerMapper {
	pm := &PlayerMapper{byType: map[string]concreteMapper{}}
	for _, m := range []concreteMapper{FootballerMapper{}, CricketerMapper{}, BowlerMapper{}} {
		pm.order = append(pm.order, m.typeCode())
		pm.byType[m.typeCode()] = m
	}
	return pm
}

func (pm *PlayerMapper) forObject(p Player) concreteMapper {
	switch p.(type) {
	case *Footballer:
		return pm.byType["footballer"]
	case *Bowler:
		return pm.byType["bowler"]
	default:
		return pm.byType["cricketer"]
	}
}

func (pm *PlayerMapper) insert(p Player) (concreteMapper, []string) {
	m := pm.forObject(p)
	return m, insert(m, p)
}

func (pm *PlayerMapper) find(id int64) (concreteMapper, Player) {
	r := playerTable[id]
	m := pm.byType[r["type"].(string)]
	return m, find(m, id, r)
}

func (pm *PlayerMapper) findAll() []Player {
	ids := make([]int64, 0, len(playerTable))
	for id := range playerTable {
		ids = append(ids, id)
	}
	sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
	var out []Player
	for _, id := range ids {
		r := playerTable[id]
		out = append(out, find(pm.byType[r["type"].(string)], id, r))
	}
	return out
}

func main() {
	players := newPlayerMapper()
	for _, t := range players.order {
		fmt.Printf("mapper chain for %s: %s\n", t, strings.Join(players.byType[t].chain(), ", "))
	}
	ann := &Footballer{PlayerBase{Name: "Ann"}, "Lions"}
	bo := &Cricketer{PlayerBase{Name: "Bo"}, 412}
	cy := &Bowler{Cricketer{PlayerBase{Name: "Cy"}, 95}, 31}
	for _, p := range []Player{ann, bo, cy} {
		m, log := players.insert(p)
		fmt.Printf("insert %s: %s saved %s\n", p.base().Name, m.name(), strings.Join(log, ", "))
	}
	m, p := players.find(3)
	fmt.Printf("find 3: %s (mapper %s)\n", p.Describe(), m.name())
	var all []string
	for _, q := range players.findAll() {
		all = append(all, q.Describe())
	}
	fmt.Println("find all:", strings.Join(all, " | "))
}
Output
mapper chain for footballer: FootballerMapper, AbstractPlayerMapper
mapper chain for cricketer: CricketerMapper, AbstractPlayerMapper
mapper chain for bowler: BowlerMapper, CricketerMapper, AbstractPlayerMapper
insert Ann: FootballerMapper saved name (Player), club (Footballer)
insert Bo: CricketerMapper saved name (Player), runs (Cricketer)
insert Cy: BowlerMapper saved name (Player), runs (Cricketer), wickets (Bowler)
find 3: Bowler Cy, runs 95, wickets 31 (mapper BowlerMapper)
find all: Footballer Ann, club Lions | Cricketer Bo, runs 412 | Bowler Cy, runs 95, wickets 31
  • Verdict: idiom. Go has no class inheritance, so each mapper struct embeds the mapper of its superclass and calls it by name, as in m.CricketerMapper.save. The free functions insert and find hold the shared steps and take the concreteMapper interface.
  • cricketer gives the Cricketer part of a *Cricketer or a *Bowler, so CricketerMapper works for both types.
RustGitHub
use std::collections::BTreeMap;

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

impl Value {
    fn text(&self) -> String {
        match self {
            Value::Text(s) => s.clone(),
            Value::Int(_) => panic!("not text"),
        }
    }
    fn int(&self) -> i64 {
        match self {
            Value::Int(n) => *n,
            Value::Text(_) => panic!("not an integer"),
        }
    }
}

type Row = BTreeMap<&'static str, Value>;

// Rust has no class inheritance, so each type holds the struct of its superclass.
#[derive(Default)]
struct PlayerBase {
    id: i64,
    name: String,
}

#[derive(Default)]
struct Footballer {
    base: PlayerBase,
    club: String,
}

#[derive(Default)]
struct Cricketer {
    base: PlayerBase,
    runs: i64,
}

#[derive(Default)]
struct Bowler {
    cricketer: Cricketer,
    wickets: i64,
}

enum Player {
    Footballer(Footballer),
    Cricketer(Cricketer),
    Bowler(Bowler),
}

impl Player {
    fn base(&mut self) -> &mut PlayerBase {
        match self {
            Player::Footballer(f) => &mut f.base,
            Player::Cricketer(c) => &mut c.base,
            Player::Bowler(b) => &mut b.cricketer.base,
        }
    }
    fn cricketer(&mut self) -> &mut Cricketer {
        match self {
            Player::Cricketer(c) => c,
            Player::Bowler(b) => &mut b.cricketer,
            Player::Footballer(_) => panic!("not a cricketer"),
        }
    }
    fn describe(&self) -> String {
        match self {
            Player::Footballer(f) => format!("Footballer {}, club {}", f.base.name, f.club),
            Player::Cricketer(c) => format!("Cricketer {}, runs {}", c.base.name, c.runs),
            Player::Bowler(b) => format!("Bowler {}, runs {}, wickets {}", b.cricketer.base.name, b.cricketer.runs, b.wickets),
        }
    }
}

// Each mapper saves and loads the fields that its type declares, and calls the
// mapper of the superclass, which it holds, for the inherited fields.
trait Mapper {
    fn type_code(&self) -> &'static str;
    fn name(&self) -> &'static str;
    fn chain(&self) -> Vec<&'static str>;
    fn create(&self) -> Player;
    fn save(&self, p: &mut Player, r: &mut Row, log: &mut Vec<&'static str>);
    fn load(&self, p: &mut Player, r: &Row);
}

struct AbstractPlayerMapper;

impl AbstractPlayerMapper {
    fn chain(&self) -> Vec<&'static str> {
        vec!["AbstractPlayerMapper"]
    }
    fn save(&self, p: &mut Player, r: &mut Row, log: &mut Vec<&'static str>) {
        r.insert("name", Value::Text(p.base().name.clone()));
        log.push("name (Player)");
    }
    fn load(&self, p: &mut Player, r: &Row) {
        p.base().name = r["name"].text();
    }
}

struct FootballerMapper {
    parent: AbstractPlayerMapper,
}

impl Mapper for FootballerMapper {
    fn type_code(&self) -> &'static str {
        "footballer"
    }
    fn name(&self) -> &'static str {
        "FootballerMapper"
    }
    fn chain(&self) -> Vec<&'static str> {
        [vec![self.name()], self.parent.chain()].concat()
    }
    fn create(&self) -> Player {
        Player::Footballer(Footballer::default())
    }
    fn save(&self, p: &mut Player, r: &mut Row, log: &mut Vec<&'static str>) {
        self.parent.save(p, r, log);
        if let Player::Footballer(f) = p {
            r.insert("club", Value::Text(f.club.clone()));
        }
        log.push("club (Footballer)");
    }
    fn load(&self, p: &mut Player, r: &Row) {
        self.parent.load(p, r);
        if let Player::Footballer(f) = p {
            f.club = r["club"].text();
        }
    }
}

struct CricketerMapper {
    parent: AbstractPlayerMapper,
}

impl Mapper for CricketerMapper {
    fn type_code(&self) -> &'static str {
        "cricketer"
    }
    fn name(&self) -> &'static str {
        "CricketerMapper"
    }
    fn chain(&self) -> Vec<&'static str> {
        [vec![self.name()], self.parent.chain()].concat()
    }
    fn create(&self) -> Player {
        Player::Cricketer(Cricketer::default())
    }
    fn save(&self, p: &mut Player, r: &mut Row, log: &mut Vec<&'static str>) {
        self.parent.save(p, r, log);
        r.insert("runs", Value::Int(p.cricketer().runs));
        log.push("runs (Cricketer)");
    }
    fn load(&self, p: &mut Player, r: &Row) {
        self.parent.load(p, r);
        p.cricketer().runs = r["runs"].int();
    }
}

struct BowlerMapper {
    parent: CricketerMapper,
}

impl Mapper for BowlerMapper {
    fn type_code(&self) -> &'static str {
        "bowler"
    }
    fn name(&self) -> &'static str {
        "BowlerMapper"
    }
    fn chain(&self) -> Vec<&'static str> {
        [vec![self.name()], self.parent.chain()].concat()
    }
    fn create(&self) -> Player {
        Player::Bowler(Bowler::default())
    }
    fn save(&self, p: &mut Player, r: &mut Row, log: &mut Vec<&'static str>) {
        self.parent.save(p, r, log);
        if let Player::Bowler(b) = p {
            r.insert("wickets", Value::Int(b.wickets));
        }
        log.push("wickets (Bowler)");
    }
    fn load(&self, p: &mut Player, r: &Row) {
        self.parent.load(p, r);
        if let Player::Bowler(b) = p {
            b.wickets = r["wickets"].int();
        }
    }
}

// The mapper for the whole hierarchy: it chooses the concrete mapper and delegates to it.
struct PlayerMapper {
    mappers: Vec<Box<dyn Mapper>>,
    table: BTreeMap<i64, Row>,
    next_id: i64,
}

impl PlayerMapper {
    fn by_type(&self, t: &str) -> &dyn Mapper {
        self.mappers.iter().find(|m| m.type_code() == t).expect("mapper").as_ref()
    }

    fn insert(&mut self, p: &mut Player) -> (&'static str, Vec<&'static str>) {
        let t = match p {
            Player::Footballer(_) => "footballer",
            Player::Cricketer(_) => "cricketer",
            Player::Bowler(_) => "bowler",
        };
        let mut r = Row::new();
        r.insert("type", Value::Text(t.to_string()));
        let mut log = Vec::new();
        let m = self.by_type(t);
        m.save(p, &mut r, &mut log);
        let name = m.name();
        p.base().id = self.next_id;
        self.table.insert(self.next_id, r);
        self.next_id += 1;
        (name, log)
    }

    fn load(&self, id: i64, r: &Row) -> (&'static str, Player) {
        let m = self.by_type(&r["type"].text());
        let mut p = m.create();
        p.base().id = id;
        m.load(&mut p, r);
        (m.name(), p)
    }

    fn find(&self, id: i64) -> (&'static str, Player) {
        self.load(id, &self.table[&id])
    }

    fn find_all(&self) -> Vec<Player> {
        self.table.iter().map(|(id, r)| self.load(*id, r).1).collect()
    }
}

fn main() {
    let mut players = PlayerMapper {
        mappers: vec![
            Box::new(FootballerMapper { parent: AbstractPlayerMapper }),
            Box::new(CricketerMapper { parent: AbstractPlayerMapper }),
            Box::new(BowlerMapper { parent: CricketerMapper { parent: AbstractPlayerMapper } }),
        ],
        table: BTreeMap::new(),
        next_id: 1,
    };
    for m in &players.mappers {
        println!("mapper chain for {}: {}", m.type_code(), m.chain().join(", "));
    }
    let base = |name: &str| PlayerBase { id: 0, name: name.to_string() };
    let mut all = vec![
        Player::Footballer(Footballer { base: base("Ann"), club: "Lions".into() }),
        Player::Cricketer(Cricketer { base: base("Bo"), runs: 412 }),
        Player::Bowler(Bowler { cricketer: Cricketer { base: base("Cy"), runs: 95 }, wickets: 31 }),
    ];
    for p in all.iter_mut() {
        let (name, log) = players.insert(p);
        println!("insert {}: {} saved {}", p.base().name, name, log.join(", "));
    }
    let (name, p) = players.find(3);
    println!("find 3: {} (mapper {})", p.describe(), name);
    let found: Vec<String> = players.find_all().iter().map(|p| p.describe()).collect();
    println!("find all: {}", found.join(" | "));
}
Output
mapper chain for footballer: FootballerMapper, AbstractPlayerMapper
mapper chain for cricketer: CricketerMapper, AbstractPlayerMapper
mapper chain for bowler: BowlerMapper, CricketerMapper, AbstractPlayerMapper
insert Ann: FootballerMapper saved name (Player), club (Footballer)
insert Bo: CricketerMapper saved name (Player), runs (Cricketer)
insert Cy: BowlerMapper saved name (Player), runs (Cricketer), wickets (Bowler)
find 3: Bowler Cy, runs 95, wickets 31 (mapper BowlerMapper)
find all: Footballer Ann, club Lions | Cricketer Bo, runs 412 | Bowler Cy, runs 95, wickets 31
  • Verdict: idiom. Rust has no class inheritance, so each mapper holds the mapper of its superclass in a parent field and calls it first. The Mapper trait gives PlayerMapper one interface for the three concrete mappers, kept as Box<dyn Mapper>.
  • The domain types hold the struct of their superclass, and Player::base and Player::cricketer give the shared parts.

Consequences

Benefits.

  • Each field is mapped in one place. The code for the fields of Player is in AbstractPlayerMapper only, so a new field in Player changes one mapper.
  • The program can save and load through the superclass. PlayerMapper gives one find and one insert for all players, and the caller does not need to know the class.
  • The structure does not depend on the table design. A change from one table to a table for each class changes the row code in the mappers, not the structure.

Liabilities.

More classes. A hierarchy of four domain classes gets five mapper classes. For a small hierarchy with one table design, a single mapper with a branch on the type can be simpler.

The two hierarchies must change together. A new subclass of Player needs a new concrete mapper, and PlayerMapper must learn its class and its type code.

Without the structure, the code for the shared fields is copied. In the following program, each mapper has its own copy of the code for the fields of Player. A later field country was added to one copy only, so the cricketer loses it.

This code runs but gives a wrong answer on purpose.

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


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


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


# Wrong: each mapper copies the code for the fields of Player. The field country
# was added later, and only one of the copies was changed.
def save_footballer(p):
    return {"name": p.name, "country": p.country, "club": p.club}


def save_cricketer(p):
    return {"name": p.name, "runs": p.runs}


rows = [save_footballer(Footballer("Ann", "NZ", "Lions")), save_cricketer(Cricketer("Bo", "NZ", 412))]
print([(r["name"], r.get("country")) for r in rows])
Output
[('Ann', 'NZ'), ('Bo', None)]

When not to use it

When there is no inheritance to map. For one class and one table, use a plain Data Mapper.

When an ORM does the mapping. SQLAlchemy, Hibernate and Entity Framework Core have this structure inside them. The program declares the hierarchy and the table design, and does not write the mappers.

The table designs. The mappers are the same for Single Table Inheritance, Class Table Inheritance and Concrete Table Inheritance. With one table, the hierarchy mapper reads the type column. With a table for each class, the concrete mapper of each class writes its own table. With a table for each concrete class, the hierarchy mapper must try each table or use a union.

Registry of mappers. Instead of a fixed list in the hierarchy mapper, each concrete mapper can add itself to a map from type code to mapper. SQLAlchemy does this with its polymorphic map.3

Related patterns. Each mapper is a Data Mapper, and the calls from a mapper to the mapper of its superclass follow the Template Method pattern.

Known uses

  • SQLAlchemy: a mapper for a subclass inherits from the mapper of its superclass. In Mapper._configure_inheritance in mapper.py at 2.0.57, each mapper takes the polymorphic_map of the mapper that it inherits from and adds its own polymorphic_identity to it.4 The docstring in mapper.py at 2.0.57 says: "An inheritance chain of mappers will all reference the same polymorphic map object. The object is used to correlate incoming result rows to target mappers."3 The documentation shows the same structure for joined, single and concrete table inheritance.5
  • Hibernate: each entity has a persister, and the class of the persister follows the table design. SingleTableEntityPersister at 6.6.9 is "implemented as a single table for all classes of the hierarchy, with a discriminator column used to determine which concrete class a row represents."6 JoinedSubclassEntityPersister uses "a separate table for each subclass"7, and UnionSubclassEntityPersister uses "a separate table for each concrete class, with all inherited attributes persisted as columns of that table."8 All three extend AbstractEntityPersister.

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Inheritance Mappers, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 12, Object-Relational Structural Patterns, Inheritance Mappers
  3. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/mapper.py, Mapper.polymorphic_map, lines 1128 to 1140
  4. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/mapper.py, Mapper._configure_inheritance, lines 1335 to 1358
  5. SQLAlchemy 2.0 documentation, Mapping Class Inheritance Hierarchies, Joined Table Inheritance; Single Table Inheritance; Concrete Table Inheritance
  6. Hibernate ORM 6.6.9 source, SingleTableEntityPersister.java, class comment, lines 56 to 68
  7. Hibernate ORM 6.6.9 source, JoinedSubclassEntityPersister.java, class comment, lines 83 to 96
  8. Hibernate ORM 6.6.9 source, UnionSubclassEntityPersister.java, class comment, lines 69 to 80

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