DEV Community

Cover image for Single Table Inheritance, Class Table Inheritance, and Concrete Class Inheritance
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Single Table Inheritance, Class Table Inheritance, and Concrete Class Inheritance

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.

people_class.png

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.

  • id is a unique key.
  • name is the name.

OrdinaryPeople

These are sensible and good ordinary people.

  • good_sense is common sense, stored as a boolean (0 or 1).

RichPeople

These are wealthy people with money and land.

  • money is money.
  • land is land.

Note: Units and other details are not considered.

PartyPeople

Party people.

  • free_time is free time.
  • middle_name is 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.

single_table_inheritance_table.png

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.

class_table_inheritance.png

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.

concrete_table_inheritance.png

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.

Reference Links

Top comments (0)