This article was originally published on bmf-tech.com.
Overview
Relational databases do not support inheritance, so it is necessary to consider how to represent object inheritance relationships in the database. This post explains three patterns to express this: Single Table Inheritance, Class Table Inheritance, and Concrete Class Inheritance.
Note: This post does not discuss the advantages and disadvantages of implementing each pattern.
Prerequisites
We will consider four classes in this example.
The structure where Party People inherits from Rich People might be a bit confusing, but as long as the concept is conveyed, it’s fine.
People
This class has attributes common to all classes.
-
idis a unique key. -
nameis the name.
OrdinaryPeople
These are sensible and good ordinary people.
-
good_senseis common sense, stored as a boolean (0 or 1).
RichPeople
These are wealthy people with money and land.
-
moneyis money. -
landis land.
Note: Units and other details are not considered.
PartyPeople
Party people.
-
free_timeis free time. -
middle_nameis the middle name.
Single Table Inheritance
Single Table Inheritance represents object inheritance relationships in a single table. The table includes a column (type) to determine the subclass.
It seems that Rails supports the implementation of STI.
Class Table Inheritance
Class Table Inheritance represents object inheritance relationships by preparing one table per class. The superclass table contains columns held by the superclass, while the subclass table contains only columns held by the subclass.
Concrete Class Inheritance
Concrete Class Inheritance represents object inheritance relationships by preparing tables that correspond only to concrete classes. Each table includes columns held by the superclass as common attributes.
Thoughts
The choice of which pattern to implement depends on the consideration of the advantages and disadvantages of table design and the cost of application logic. Please point out any misleading or incorrect parts.




Top comments (0)