Sunday, 11 August 2013

Single Table Inheritance Design Pattern

🚀 Master Software Architecture & Java!

Subscribe to Ram N Java for clear, beginner-friendly design pattern tutorials and tutorials.

🔔 Subscribe Now

What is the Single Table Inheritance Pattern?

The Single Table Inheritance pattern is an object-relational structural pattern from Martin Fowler's Patterns of Enterprise Application Architecture. It represents an entire inheritance hierarchy of classes within one single database table containing columns for all fields across all classes.

Why Do We Need It?

Relational databases do not support object-oriented inheritance natively. When multiple subclasses inherit from a common parent class, we need a clean strategy to store their shared and specific properties in relational tables.

Beginner-Friendly Example

Consider an employee management hierarchy:

  • Employee (Superclass): Contains common fields: employee_id, name, phone, email, and type (discriminator).
  • Salaried Employee (Subclass): Inherits from Employee and adds salary.
  • Hourly Employee (Subclass): Inherits from Employee and adds hours and rate.

Database Table Structure:

Instead of creating multiple tables, we map all classes into a single employee table:

  • Columns: employee_id, name, phone, email, type, salary, rate, hours
  • For a salaried employee, the rate and hours columns remain NULL.
  • For an hourly employee, the salary column remains NULL.
  • The type column identifies which subclass the row represents.

Key Advantages

  • Fast Queries: No SQL JOIN operations are needed to retrieve subclass data.
  • Simple Schema: Everything resides in a single table, simplifying data management.
  • Easy Refactoring: Moving fields up or down the hierarchy does not require altering database table structures.

Related Videos to Watch Next


Click here to watch in Youtube : https://www.youtube.com/watch?v=gfkLKNRt_oQ

Click the below Image to Enlarge
Single Table Inheritance Design Pattern














See also:

  • All Design Patterns Links
  • No comments:

    Post a Comment

    Tutorials