🚀 Master Software Architecture & Java!
Subscribe to Ram N Java for clear, beginner-friendly design pattern tutorials and tutorials.
🔔 Subscribe NowWhat 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, andtype(discriminator). - Salaried Employee (Subclass): Inherits from
Employeeand addssalary. - Hourly Employee (Subclass): Inherits from
Employeeand addshoursandrate.
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
rateandhourscolumns remainNULL. - For an hourly employee, the
salarycolumn remainsNULL. - The
typecolumn 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 |
No comments:
Post a Comment