Patterncore
Single Table Inheritance
Also called single table inheritance pattern, table per hierarchy, TPH, single-table mapping.
Single Table Inheritance stores all the classes of an inheritance hierarchy in one table, with a column for each field of each class and a type column that names the class of each row.
- Family
- architectural
- Intent
- Represents an inheritance hierarchy of classes as a single table that has columns for all the fields of the various classes.
Intent
Single Table Inheritance "Represents an inheritance hierarchy of classes as a single table that has columns for all the fields of the various classes."1 A type column in each row names the class of the object that the row holds.
Problem
"Relational databases don't support inheritance, so when mapping from objects to databases we have to consider how to represent our nice inheritance structures in relational tables."1 A program has a class Player with the subclasses Footballer and Cricketer, and Bowler is a kind of Cricketer. Code asks for all players, or for all cricketers, and expects objects of the right subclass. A table for each class needs joins to build one object. Fowler gives the goal of this pattern: "When mapping to a relational database, we try to minimize the joins that can quickly mount up when processing an inheritance structure in multiple tables."1
Solution
"Single Table Inheritance maps all fields of all classes of an inheritance structure into a single table."1 Each row holds one object. The fields of its class are in their columns, and the columns of the other classes are null. SQLAlchemy describes the same layout: "A particular subclass that has attributes unique to that class will persist them within columns in the table that are otherwise NULL if the row refers to a different kind of object."2
One more column, the discriminator, holds a code for the class of the row. The mapper writes it on insert, and on load it reads it first to know which class to build. Entity Framework Core says: "TPH uses a single table to store the data for all types in the hierarchy, and a discriminator column is used to identify which type each row represents."3
classes table player
Player(name) id | type | name | club | runs | wickets
|- Footballer(club) 1 | footballer | Ann | Lions | null | null
|- Cricketer(runs) 2 | cricketer | Bo | null | 412 | null
|- Bowler(wickets) 3 | bowler | Cy | null | 95 | 31
all players: select * from player
cricketers: select * from player where type in ('cricketer', 'bowler')
The participants are the class hierarchy; the single table, with the union of the columns of all the classes; the discriminator column; and the mapper, which writes the code of the class with each row and uses it to choose the class on load.
The following program saves a footballer and a cricketer in one table, and builds each object again from the type column.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("""create table player (id integer primary key, type text not null,
name text, club text, runs integer)""")
class Player:
def __init__(self, name):
self.name = name
class Footballer(Player):
def __init__(self, name, club):
super().__init__(name)
self.club = club
class Cricketer(Player):
def __init__(self, name, runs):
super().__init__(name)
self.runs = runs
TYPES = {"footballer": Footballer, "cricketer": Cricketer}
def insert(p):
# One table for the whole hierarchy; the type column says which class the row is.
kind = {Footballer: "footballer", Cricketer: "cricketer"}[type(p)]
db.execute("insert into player (type, name, club, runs) values (?, ?, ?, ?)",
(kind, p.name, getattr(p, "club", None), getattr(p, "runs", None)))
def load(row):
id, kind, name, club, runs = row
return Footballer(name, club) if kind == "footballer" else Cricketer(name, runs)
insert(Footballer("Ann", "Lions"))
insert(Cricketer("Bo", 412))
print(db.execute("select * from player").fetchall())
print([type(load(r)).__name__ for r in db.execute("select * from player")])
[(1, 'footballer', 'Ann', 'Lions', None), (2, 'cricketer', 'Bo', None, 412)]
['Footballer', 'Cricketer']
Example
Each example file saves a footballer, a cricketer and a bowler in one player table and prints the rows. Each row has values only in the columns of its class, and null in the others. It loads all the players, and the type column chooses the class of each object. A query for cricketers selects the rows of type cricketer and bowler, because a bowler is a cricketer. The last line counts the null cells in the three subclass columns: 5 of 9. The Python file uses SQLite. The JavaScript, Java, Go and Rust files keep the table in memory as rows with a null for each unused column.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("""create table player (id integer primary key, type text not null, name text,
club text, runs integer, wickets integer)""")
class Player:
def __init__(self, name, id=None):
self.id, self.name = id, name
class Footballer(Player):
def __init__(self, name, club, id=None):
super().__init__(name, id)
self.club = club
def describe(self):
return f"Footballer {self.name}, club {self.club}"
class Cricketer(Player):
def __init__(self, name, runs, id=None):
super().__init__(name, id)
self.runs = runs
def describe(self):
return f"Cricketer {self.name}, runs {self.runs}"
class Bowler(Cricketer):
def __init__(self, name, runs, wickets, id=None):
super().__init__(name, runs, id)
self.wickets = wickets
def describe(self):
return f"Bowler {self.name}, runs {self.runs}, wickets {self.wickets}"
# The discriminator: one value for each concrete class, kept in the type column.
TYPE_OF = {Footballer: "footballer", Cricketer: "cricketer", Bowler: "bowler"}
SUBTYPES = {"cricketer": ["cricketer", "bowler"]}
def insert(p):
# Each class writes its own fields; the columns of the other classes stay null.
sql = "insert into player (type, name, club, runs, wickets) values (?, ?, ?, ?, ?)"
values = (TYPE_OF[type(p)], p.name, getattr(p, "club", None),
getattr(p, "runs", None), getattr(p, "wickets", None))
p.id = db.execute(sql, values).lastrowid
def load(row):
id, kind, name, club, runs, wickets = row
if kind == "footballer":
return Footballer(name, club, id)
if kind == "cricketer":
return Cricketer(name, runs, id)
return Bowler(name, runs, wickets, id)
def find_all(kind=None):
if kind is None:
rows = db.execute("select * from player order by id")
else:
kinds = SUBTYPES.get(kind, [kind])
marks = ", ".join("?" for _ in kinds)
rows = db.execute(f"select * from player where type in ({marks}) order by id", kinds)
return [load(r) for r in rows]
def show(v):
return "null" if v is None else str(v)
insert(Footballer("Ann", "Lions"))
insert(Cricketer("Bo", 412))
insert(Bowler("Cy", 95, 31))
for row in db.execute("select * from player order by id"):
print("row:", " ".join(show(v) for v in row))
for p in find_all():
print("loaded:", p.describe())
print("cricketers:", ", ".join(p.name for p in find_all("cricketer")))
nulls = db.execute("""select sum((club is null) + (runs is null) + (wickets is null)),
3 * count(*) from player""").fetchone()
print(f"null cells in subclass columns: {nulls[0]} of {nulls[1]}")
row: 1 footballer Ann Lions null null
row: 2 cricketer Bo null 412 null
row: 3 bowler Cy null 95 31
loaded: Footballer Ann, club Lions
loaded: Cricketer Bo, runs 412
loaded: Bowler Cy, runs 95, wickets 31
cricketers: Bo, Cy
null cells in subclass columns: 5 of 9
- Verdict: idiom.
TYPE_OFmaps each concrete class to its code in thetypecolumn, andloadreads the code to choose the class.getattr(p, "club", None)gives null for a field that the class does not have. find_all("cricketer")selects the codes ofCricketerand its subclassBowler, as a polymorphic query does.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
// One table for the whole hierarchy. A missing value is null.
record Row(String type, String name, String club, Integer runs, Integer wickets) {}
static final Map<Long, Row> PLAYER = new TreeMap<>();
static long lastId = 0;
abstract static class Player {
Long id;
final String name;
Player(String name) {
this.name = name;
}
abstract String describe();
}
static class Footballer extends Player {
final String club;
Footballer(String name, String club) {
super(name);
this.club = club;
}
String describe() {
return "Footballer " + name + ", club " + club;
}
}
static class Cricketer extends Player {
final int runs;
Cricketer(String name, int runs) {
super(name);
this.runs = runs;
}
String describe() {
return "Cricketer " + name + ", runs " + runs;
}
}
static class Bowler extends Cricketer {
final int wickets;
Bowler(String name, int runs, int wickets) {
super(name, runs);
this.wickets = wickets;
}
@Override
String describe() {
return "Bowler " + name + ", runs " + runs + ", wickets " + wickets;
}
}
static final Map<String, List<String>> SUBTYPES = Map.of("cricketer", List.of("cricketer", "bowler"));
static void insert(Player p) {
// Each class writes its own fields; the columns of the other classes stay null.
Row row;
if (p instanceof Bowler b) {
row = new Row("bowler", b.name, null, b.runs, b.wickets);
} else if (p instanceof Cricketer c) {
row = new Row("cricketer", c.name, null, c.runs, null);
} else {
Footballer f = (Footballer) p;
row = new Row("footballer", f.name, f.club, null, null);
}
p.id = ++lastId;
PLAYER.put(p.id, row);
}
static Player load(long id, Row r) {
Player p = switch (r.type()) {
case "footballer" -> new Footballer(r.name(), r.club());
case "cricketer" -> new Cricketer(r.name(), r.runs());
default -> new Bowler(r.name(), r.runs(), r.wickets());
};
p.id = id;
return p;
}
static List<Player> findAll(String kind) {
List<String> kinds = kind == null ? null : SUBTYPES.getOrDefault(kind, List.of(kind));
List<Player> result = new ArrayList<>();
for (var e : PLAYER.entrySet()) {
if (kinds == null || kinds.contains(e.getValue().type())) {
result.add(load(e.getKey(), e.getValue()));
}
}
return result;
}
static String show(Object v) {
return v == null ? "null" : v.toString();
}
public static void main(String[] args) {
insert(new Footballer("Ann", "Lions"));
insert(new Cricketer("Bo", 412));
insert(new Bowler("Cy", 95, 31));
for (var e : PLAYER.entrySet()) {
Row r = e.getValue();
System.out.println("row: " + e.getKey() + " " + r.type() + " " + r.name() + " "
+ show(r.club()) + " " + show(r.runs()) + " " + show(r.wickets()));
}
for (Player p : findAll(null)) {
System.out.println("loaded: " + p.describe());
}
List<String> names = new ArrayList<>();
for (Player p : findAll("cricketer")) {
names.add(p.name);
}
System.out.println("cricketers: " + String.join(", ", names));
int nulls = 0;
for (Row r : PLAYER.values()) {
nulls += (r.club() == null ? 1 : 0) + (r.runs() == null ? 1 : 0) + (r.wickets() == null ? 1 : 0);
}
System.out.println("null cells in subclass columns: " + nulls + " of " + 3 * PLAYER.size());
}
}
row: 1 footballer Ann Lions null null
row: 2 cricketer Bo null 412 null
row: 3 bowler Cy null 95 31
loaded: Footballer Ann, club Lions
loaded: Cricketer Bo, runs 412
loaded: Bowler Cy, runs 95, wickets 31
cricketers: Bo, Cy
null cells in subclass columns: 5 of 9
- Verdict: idiom. A row is a record with boxed
Integerfields, sonullcan stand for an unused column.insertuses pattern matching forinstanceofand testsBowlerfirst, andloaduses aswitchon the type code. - With JPA or Hibernate,
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)on the root class and@DiscriminatorValueon each subclass give the same mapping.
// A stand-in for the database: one table for the whole hierarchy.
// Columns: type, name, club, runs, wickets. A missing value is null.
const playerTable = new Map();
let lastId = 0;
class Player {
constructor(name, id = null) {
this.id = id;
this.name = name;
}
}
class Footballer extends Player {
constructor(name, club, id = null) {
super(name, id);
this.club = club;
}
describe() {
return `Footballer ${this.name}, club ${this.club}`;
}
}
class Cricketer extends Player {
constructor(name, runs, id = null) {
super(name, id);
this.runs = runs;
}
describe() {
return `Cricketer ${this.name}, runs ${this.runs}`;
}
}
class Bowler extends Cricketer {
constructor(name, runs, wickets, id = null) {
super(name, runs, id);
this.wickets = wickets;
}
describe() {
return `Bowler ${this.name}, runs ${this.runs}, wickets ${this.wickets}`;
}
}
// The discriminator: one value for each concrete class, kept in the type column.
function typeOf(p) {
if (p instanceof Bowler) return "bowler";
if (p instanceof Cricketer) return "cricketer";
return "footballer";
}
const SUBTYPES = { cricketer: ["cricketer", "bowler"] };
function insert(p) {
// Each class writes its own fields; the columns of the other classes stay null.
p.id = ++lastId;
playerTable.set(p.id, {
type: typeOf(p),
name: p.name,
club: p.club ?? null,
runs: p.runs ?? null,
wickets: p.wickets ?? null,
});
}
function load(id, r) {
if (r.type === "footballer") return new Footballer(r.name, r.club, id);
if (r.type === "cricketer") return new Cricketer(r.name, r.runs, id);
return new Bowler(r.name, r.runs, r.wickets, id);
}
function findAll(kind = null) {
const kinds = kind === null ? null : SUBTYPES[kind] ?? [kind];
return [...playerTable]
.filter(([, r]) => kinds === null || kinds.includes(r.type))
.map(([id, r]) => load(id, r));
}
const show = (v) => (v === null ? "null" : String(v));
insert(new Footballer("Ann", "Lions"));
insert(new Cricketer("Bo", 412));
insert(new Bowler("Cy", 95, 31));
for (const [id, r] of playerTable) {
console.log(`row: ${[id, r.type, r.name, r.club, r.runs, r.wickets].map(show).join(" ")}`);
}
for (const p of findAll()) console.log(`loaded: ${p.describe()}`);
console.log(`cricketers: ${findAll("cricketer").map((p) => p.name).join(", ")}`);
let nulls = 0;
for (const r of playerTable.values()) {
nulls += [r.club, r.runs, r.wickets].filter((v) => v === null).length;
}
console.log(`null cells in subclass columns: ${nulls} of ${3 * playerTable.size}`);
row: 1 footballer Ann Lions null null
row: 2 cricketer Bo null 412 null
row: 3 bowler Cy null 95 31
loaded: Footballer Ann, club Lions
loaded: Cricketer Bo, runs 412
loaded: Bowler Cy, runs 95, wickets 31
cricketers: Bo, Cy
null cells in subclass columns: 5 of 9
- Verdict: idiom.
typeOfusesinstanceofand testsBowlerbeforeCricketer, because a bowler is also an instance ofCricketer.p.club ?? nullwrites null for a field that the class does not have. - The table is a
Mapof plain objects with one property for each column.
package main
import (
"fmt"
"sort"
"strings"
)
// row is one row of the single player table. A nil pointer is a null column.
type row struct {
Type string
Name string
Club *string
Runs *int
Wickets *int
}
var (
playerTable = map[int64]row{}
lastID int64
)
// Player is the interface of the hierarchy; Go has no class inheritance, so
// Bowler embeds Cricketer to reuse its fields.
type Player interface {
Describe() string
PlayerName() string
}
type Footballer struct {
ID int64
Name string
Club string
}
type Cricketer struct {
ID int64
Name string
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)
}
func (f *Footballer) PlayerName() string { return f.Name }
func (c *Cricketer) PlayerName() string { return c.Name }
var subtypes = map[string][]string{"cricketer": {"cricketer", "bowler"}}
// insert writes the fields of each class; the columns of the other classes stay nil.
func insert(p Player) {
lastID++
switch v := p.(type) {
case *Footballer:
v.ID = lastID
playerTable[lastID] = row{"footballer", v.Name, &v.Club, nil, nil}
case *Bowler:
v.ID = lastID
playerTable[lastID] = row{"bowler", v.Name, nil, &v.Runs, &v.Wickets}
case *Cricketer:
v.ID = lastID
playerTable[lastID] = row{"cricketer", v.Name, nil, &v.Runs, nil}
}
}
func load(id int64, r row) Player {
switch r.Type {
case "footballer":
return &Footballer{id, r.Name, *r.Club}
case "cricketer":
return &Cricketer{id, r.Name, *r.Runs}
default:
return &Bowler{Cricketer{id, r.Name, *r.Runs}, *r.Wickets}
}
}
func ids() []int64 {
keys := make([]int64, 0, len(playerTable))
for k := range playerTable {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
return keys
}
func findAll(kind string) []Player {
kinds := subtypes[kind]
if kinds == nil && kind != "" {
kinds = []string{kind}
}
var result []Player
for _, id := range ids() {
r := playerTable[id]
match := kind == ""
for _, k := range kinds {
if r.Type == k {
match = true
}
}
if match {
result = append(result, load(id, r))
}
}
return result
}
func showString(p *string) string {
if p == nil {
return "null"
}
return *p
}
func showInt(p *int) string {
if p == nil {
return "null"
}
return fmt.Sprint(*p)
}
func main() {
insert(&Footballer{Name: "Ann", Club: "Lions"})
insert(&Cricketer{Name: "Bo", Runs: 412})
insert(&Bowler{Cricketer{Name: "Cy", Runs: 95}, 31})
for _, id := range ids() {
r := playerTable[id]
fmt.Println("row:", id, r.Type, r.Name, showString(r.Club), showInt(r.Runs), showInt(r.Wickets))
}
for _, p := range findAll("") {
fmt.Println("loaded:", p.Describe())
}
var names []string
for _, p := range findAll("cricketer") {
names = append(names, p.PlayerName())
}
fmt.Println("cricketers:", strings.Join(names, ", "))
nulls := 0
for _, r := range playerTable {
if r.Club == nil {
nulls++
}
if r.Runs == nil {
nulls++
}
if r.Wickets == nil {
nulls++
}
}
fmt.Printf("null cells in subclass columns: %d of %d\n", nulls, 3*len(playerTable))
}
row: 1 footballer Ann Lions null null
row: 2 cricketer Bo null 412 null
row: 3 bowler Cy null 95 31
loaded: Footballer Ann, club Lions
loaded: Cricketer Bo, runs 412
loaded: Bowler Cy, runs 95, wickets 31
cricketers: Bo, Cy
null cells in subclass columns: 5 of 9
- Verdict: idiom. Go has no class inheritance, so the hierarchy is an interface, and
BowlerembedsCricketerto reuse its fields. A column that can be null is a pointer, and a type switch ininsertchooses the type code. - Go maps have no order, so
idssorts the keys before each scan of the table.
use std::collections::BTreeMap;
// One row of the single player table. None is a null column.
struct Row {
kind: &'static str,
name: String,
club: Option<String>,
runs: Option<i64>,
wickets: Option<i64>,
}
// Rust has no class inheritance, so the hierarchy is an enum with one variant
// for each concrete class.
enum Player {
Footballer { name: String, club: String },
Cricketer { name: String, runs: i64 },
Bowler { name: String, runs: i64, wickets: i64 },
}
impl Player {
fn name(&self) -> &str {
match self {
Player::Footballer { name, .. } | Player::Cricketer { name, .. } | Player::Bowler { name, .. } => name,
}
}
fn describe(&self) -> String {
match self {
Player::Footballer { name, club } => format!("Footballer {}, club {}", name, club),
Player::Cricketer { name, runs } => format!("Cricketer {}, runs {}", name, runs),
Player::Bowler { name, runs, wickets } => format!("Bowler {}, runs {}, wickets {}", name, runs, wickets),
}
}
}
#[derive(Default)]
struct Db {
player: BTreeMap<i64, Row>,
last_id: i64,
}
impl Db {
// Each variant writes its own fields; the columns of the other classes stay None.
fn insert(&mut self, p: &Player) -> i64 {
let row = match p {
Player::Footballer { name, club } => Row { kind: "footballer", name: name.clone(), club: Some(club.clone()), runs: None, wickets: None },
Player::Cricketer { name, runs } => Row { kind: "cricketer", name: name.clone(), club: None, runs: Some(*runs), wickets: None },
Player::Bowler { name, runs, wickets } => Row { kind: "bowler", name: name.clone(), club: None, runs: Some(*runs), wickets: Some(*wickets) },
};
self.last_id += 1;
self.player.insert(self.last_id, row);
self.last_id
}
fn load(r: &Row) -> Player {
let name = r.name.clone();
match r.kind {
"footballer" => Player::Footballer { name, club: r.club.clone().unwrap() },
"cricketer" => Player::Cricketer { name, runs: r.runs.unwrap() },
_ => Player::Bowler { name, runs: r.runs.unwrap(), wickets: r.wickets.unwrap() },
}
}
fn find_all(&self, kind: Option<&str>) -> Vec<Player> {
let kinds: Option<Vec<&str>> = kind.map(|k| if k == "cricketer" { vec!["cricketer", "bowler"] } else { vec![k] });
self.player
.values()
.filter(|r| kinds.as_ref().map_or(true, |ks| ks.contains(&r.kind)))
.map(Db::load)
.collect()
}
}
fn show<T: ToString>(v: &Option<T>) -> String {
v.as_ref().map_or("null".to_string(), |x| x.to_string())
}
fn main() {
let mut db = Db::default();
db.insert(&Player::Footballer { name: "Ann".into(), club: "Lions".into() });
db.insert(&Player::Cricketer { name: "Bo".into(), runs: 412 });
db.insert(&Player::Bowler { name: "Cy".into(), runs: 95, wickets: 31 });
for (id, r) in &db.player {
println!("row: {} {} {} {} {} {}", id, r.kind, r.name, show(&r.club), show(&r.runs), show(&r.wickets));
}
for p in db.find_all(None) {
println!("loaded: {}", p.describe());
}
let names: Vec<String> = db.find_all(Some("cricketer")).iter().map(|p| p.name().to_string()).collect();
println!("cricketers: {}", names.join(", "));
let nulls: usize = db.player.values().map(|r| r.club.is_none() as usize + r.runs.is_none() as usize + r.wickets.is_none() as usize).sum();
println!("null cells in subclass columns: {} of {}", nulls, 3 * db.player.len());
}
row: 1 footballer Ann Lions null null
row: 2 cricketer Bo null 412 null
row: 3 bowler Cy null 95 31
loaded: Footballer Ann, club Lions
loaded: Cricketer Bo, runs 412
loaded: Bowler Cy, runs 95, wickets 31
cricketers: Bo, Cy
null cells in subclass columns: 5 of 9
- Verdict: idiom. Rust has no class inheritance, so the hierarchy is an
enumwith one variant for each concrete class, and the type code comes from amatchon the variant. A column that can be null is anOption. find_allturns the kindcricketerinto the codescricketerandbowler, as a polymorphic query does.
Consequences
Benefits.
- No joins. "Single table inheritance has the advantage of simplicity compared to joined table inheritance; queries are much more efficient as only one table needs to be involved in order to load objects of every represented class."2 The Hibernate guide says that "the single table strategy performs the best since it requires access to one table only."4
- Polymorphic queries are simple. A query for the base class reads one table, and a query for a subclass adds a condition on the type column.
- The hierarchy can change. Fowler's book notes that a field can move up or down the hierarchy without a change to the table.5
Liabilities.
Columns that a subclass needs cannot be NOT NULL. A column for the runs of a cricketer is null in each footballer row, so the database cannot require it. "Because all subclass columns are stored in a single table, it’s not possible to use NOT NULL constraints anymore, so integrity checks must be moved either into the data access layer or enforced through CHECK or TRIGGER constraints."4 Entity Framework Core does the same: "Database columns are automatically made nullable as necessary when using TPH mapping."3
Wasted space and a wide table. Each row has a null cell for each field of the other classes. With many subclasses, the table has many columns and most of each row is empty.
The class must come from the type column, not from the data. A mapper without a discriminator must guess the class from the columns that are not null. In the following program, a new cricketer who has not batted yet has no runs, and the mapper loads the cricketer as a plain player.
This code runs but gives a wrong answer on purpose.
import sqlite3
db = sqlite3.connect(":memory:")
# No type column: the mapper guesses the class from the columns that are not null.
db.executescript("""
create table player (id integer primary key, name text, club text, runs integer);
insert into player (name, club, runs) values ('Ann', 'Lions', null);
-- Cy is a new cricketer who has not batted yet, so runs is null.
insert into player (name, club, runs) values ('Cy', null, null);
""")
def guess(club, runs):
if club is not None:
return "Footballer"
if runs is not None:
return "Cricketer"
return "Player"
print([(n, guess(c, r)) for n, c, r in db.execute("select name, club, runs from player")])
[('Ann', 'Footballer'), ('Cy', 'Player')]
The fix is a type column that is NOT NULL, written by the mapper from the class of the object.
One name for each column. Two subclasses that have fields with the same name and different meanings need different column names, because they share the table.
When not to use it
When the subclasses have many fields of their own. The table becomes wide and sparse. Use Class Table Inheritance or Concrete Table Inheritance.
When the database must check the fields of each subclass. If each subclass column must be NOT NULL, or must have its own foreign keys, a table for each class lets the database check them.
When other applications read the table. Rows of different kinds in one table are harder to read for code that does not know the hierarchy.
Variants and related patterns
Class Table Inheritance and Concrete Table Inheritance. The other two ways to map a hierarchy: one table for each class, or one table for each concrete class. SQLAlchemy supports all three and notes that "The most common forms of inheritance are single and joined table".2 Entity Framework Core gives this advice: "In summary, TPH is usually fine for most applications, and is a good default for a wide range of scenarios".3 See Class Table Inheritance and Concrete Table Inheritance.
Mixed strategies. One hierarchy can use one table for some classes and other tables for others. Inheritance Mappers organizes the mapper classes for any of the three strategies.
Known uses
- SQLAlchemy: a subclass without its own
__tablename__, withpolymorphic_onset to the discriminator column in the base class andpolymorphic_identityin each subclass.2 In mapper.py at 2.0.57,_set_polymorphic_identitysets the discriminator attribute of an object to thepolymorphic_identityof its mapper, and it raises an error for a mapper that is markedpolymorphic_abstract.6 - Entity Framework Core, for .NET: table-per-hierarchy is the default mapping of a hierarchy, with a
Discriminatorcolumn.3 - Hibernate and Jakarta Persistence:
@Inheritance(strategy = InheritanceType.SINGLE_TABLE). "When omitting an explicit inheritance strategy (e.g. @Inheritance ), Jakarta Persistence will choose the SINGLE_TABLE strategy by default."4 - Ruby on Rails: an Active Record model with a
typecolumn stores its subclasses in one table.
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Single Table Inheritance, pattern summary
- SQLAlchemy 2.0 documentation, Mapping Class Inheritance Hierarchies, Single Table Inheritance; Joined Table Inheritance
- Entity Framework Core documentation, Inheritance, Table-per-hierarchy and discriminator configuration; Summary and guidance
- Hibernate ORM 6.6 User Guide, 3.14.2. Single table
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 12, Object-Relational Structural Patterns, Single Table Inheritance
- SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/mapper.py, Mapper._configure_polymorphic_setter, _set_polymorphic_identity, lines 1987 to 2010
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 8P897X Edit this page History Report an error Markdown