Skip to content

Commit c5a6862

Browse files
authored
feat: Implemented the Table Inheritance pattern (iluwatar#3105)
* sample classes and tests * sample classes and tests * read me addition * fix violations * fix quality (coverage) * fix quality (coverage) iluwatar#2 * resolved comments
1 parent eb7a0df commit c5a6862

File tree

10 files changed

+745
-0
lines changed

10 files changed

+745
-0
lines changed

pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@
218218
<module>function-composition</module>
219219
<module>microservices-distributed-tracing</module>
220220
<module>microservices-idempotent-consumer</module>
221+
<module>table-inheritance</module>
221222
</modules>
222223
<repositories>
223224
<repository>

table-inheritance/README.md

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
---
2+
title: "Table Inheritance Pattern in Java: Modeling Hierarchical Data in Relational Databases"
3+
shortTitle: Table Inheritance
4+
description: "Explore the Table Inheritance pattern in Java with real-world examples, database schema, and tutorials. Learn how to model class hierarchies elegantly in relational databases."
5+
category: Data Access Pattern, Structural Pattern
6+
language: en
7+
tag:
8+
- Decoupling
9+
- Inheritance
10+
- Polymorphism
11+
- Object Mapping
12+
- Persistence
13+
- Data Transformation
14+
---
15+
16+
## Also Known As
17+
- Class Table Inheritance
18+
---
19+
20+
## Intent of Table Inheritance Pattern
21+
The Table Inheritance pattern models a class hierarchy in a relational database by creating
22+
separate tables for each class in the hierarchy. These tables share a common primary key, which in
23+
subclass tables also serves as a foreign key referencing the primary key of the base class table.
24+
This linkage maintains relationships and effectively represents the inheritance structure. This pattern
25+
enables the organization of complex data models, particularly when subclasses have unique properties
26+
that must be stored in distinct tables.
27+
28+
---
29+
30+
## Detailed Explanation of Table Inheritance Pattern with Real-World Examples
31+
32+
### Real-World Example
33+
Consider a **Vehicle Management System** with a `Vehicle` superclass and subclasses like `Car` and `Truck`.
34+
35+
- The **Vehicle Table** stores attributes common to all vehicles, such as `make`, `model`, and `year`. Its primary key (`id`) uniquely identifies each vehicle.
36+
- The **Car Table** and **Truck Table** store attributes specific to their respective types, such as `numberOfDoors` for cars and `payloadCapacity` for trucks.
37+
- The `id` column in the **Car Table** and **Truck Table** serves as both the primary key for those tables and a foreign key referencing the `id` in the **Vehicle Table**.
38+
39+
This setup ensures each subclass entry corresponds to a base class entry, maintaining the inheritance relationship while keeping subclass-specific data in their own tables.
40+
41+
### In Plain Words
42+
In table inheritance, each class in the hierarchy is represented by a separate table, which
43+
allows for a clear distinction between shared attributes (stored in the base class table) and
44+
specific attributes (stored in subclass tables).
45+
46+
### Martin Fowler Says
47+
48+
Relational databases don't support inheritance, which creates a mismatch when mapping objects.
49+
To fix this, Table Inheritance uses a separate table for each class in the hierarchy while maintaining
50+
relationships through foreign keys, making it easier to link the classes together in the database.
51+
52+
For more detailed information, refer to Martin Fowler's article on [Class Table Inheritance](https://martinfowler.com/eaaCatalog/classTableInheritance.html).
53+
54+
55+
## Programmatic Example of Table Inheritance Pattern in Java
56+
57+
58+
The `Vehicle` class will be the superclass, and we will have `Car` and `Truck` as subclasses that extend
59+
`Vehicle`. The `Vehicle` class will store common attributes, while `Car` and `Truck` will store
60+
attributes specific to those subclasses.
61+
62+
### Key Aspects of the Pattern:
63+
64+
1. **Superclass (`Vehicle`)**:
65+
The `Vehicle` class stores attributes shared by all vehicle types, such as:
66+
- `make`: The manufacturer of the vehicle.
67+
- `model`: The model of the vehicle.
68+
- `year`: The year the vehicle was manufactured.
69+
- `id`: A unique identifier for the vehicle.
70+
71+
These attributes are stored in the **`Vehicle` table** in the database.
72+
73+
2. **Subclass (`Car` and `Truck`)**:
74+
Each subclass (`Car` and `Truck`) stores attributes specific to that vehicle type:
75+
- `Car`: Has an additional attribute `numberOfDoors` representing the number of doors the car has.
76+
- `Truck`: Has an additional attribute `payloadCapacity` representing the payload capacity of the truck.
77+
78+
These subclass-specific attributes are stored in the **`Car` and `Truck` tables**.
79+
80+
3. **Foreign Key Relationship**:
81+
Each subclass (`Car` and `Truck`) contains the `id` field which acts as a **foreign key** that
82+
references the primary key (`id`) of the superclass (`Vehicle`). This foreign key ensures the
83+
relationship between the common attributes in the `Vehicle` table and the specific attributes in the
84+
subclass tables (`Car` and `Truck`).
85+
86+
87+
```java
88+
/**
89+
* Superclass
90+
* Represents a generic vehicle with basic attributes like make, model, year, and ID.
91+
*/
92+
public class Vehicle {
93+
private String make;
94+
private String model;
95+
private int year;
96+
private int id;
97+
98+
// Constructor, getters, and setters...
99+
}
100+
101+
/**
102+
* Represents a car, which is a subclass of Vehicle.
103+
*/
104+
public class Car extends Vehicle {
105+
private int numberOfDoors;
106+
107+
// Constructor, getters, and setters...
108+
}
109+
110+
/**
111+
* Represents a truck, which is a subclass of Vehicle.
112+
*/
113+
public class Truck extends Vehicle {
114+
private int payloadCapacity;
115+
116+
// Constructor, getters, and setters...
117+
}
118+
```
119+
120+
121+
122+
## Table Inheritance Pattern Class Diagram
123+
124+
125+
<img src="etc/class-diagram.png" width="400" height="500" />
126+
127+
128+
129+
130+
131+
132+
## Table Inheritance Pattern Database Schema
133+
134+
### Vehicle Table
135+
| Column | Description |
136+
|--------|-------------------------------------|
137+
| id | Primary key |
138+
| make | The make of the vehicle |
139+
| model | The model of the vehicle |
140+
| year | The manufacturing year of the vehicle |
141+
142+
### Car Table
143+
| Column | Description |
144+
|------------------|-------------------------------------|
145+
| id | Foreign key referencing `Vehicle(id)` |
146+
| numberOfDoors | Number of doors in the car |
147+
148+
### Truck Table
149+
| Column | Description |
150+
|-------------------|-------------------------------------|
151+
| id | Foreign key referencing `Vehicle(id)` |
152+
| payloadCapacity | Payload capacity of the truck |
153+
154+
---
155+
156+
## When to Use the Table Inheritance Pattern in Java
157+
158+
- When your application requires a clear mapping of an object-oriented class hierarchy to relational tables.
159+
- When subclasses have unique attributes that do not fit into a single base table.
160+
- When scalability and normalization of data are important considerations.
161+
- When you need to separate concerns and organize data in a way that each subclass has its own
162+
table but maintains relationships with the superclass.
163+
164+
## Table Inheritance Pattern Java Tutorials
165+
166+
- [Software Patterns Lexicon: Class Table Inheritance](https://softwarepatternslexicon.com/patterns-sql/4/4/2/)
167+
- [Martin Fowler: Class Table Inheritance](http://thierryroussel.free.fr/java/books/martinfowler/www.martinfowler.com/isa/classTableInheritance.html)
168+
169+
---
170+
171+
## Real-World Applications of Table Inheritance Pattern in Java
172+
173+
- **Vehicle Management System**: Used to store different types of vehicles like Car and Truck in separate tables but maintain a relationship through a common superclass `Vehicle`.
174+
- **E-Commerce Platforms**: Where different product types, such as Clothing, Electronics, and Furniture, are stored in separate tables with shared attributes in a superclass `Product`.
175+
176+
## Benefits and Trade-offs of Table Inheritance Pattern
177+
178+
### Benefits
179+
180+
- **Clear Structure**: Each class has its own table, making the data model easier to maintain and understand.
181+
- **Scalability**: Each subclass can be extended independently without affecting the other tables, making the system more scalable.
182+
- **Data Normalization**: Helps avoid data redundancy and keeps the schema normalized.
183+
184+
### Trade-offs
185+
186+
- **Multiple Joins**: Retrieving data that spans multiple subclasses may require joining multiple tables, which could lead to performance issues.
187+
- **Increased Complexity**: Managing relationships between tables and maintaining integrity can become more complex.
188+
- **Potential for Sparse Tables**: Subclasses with fewer attributes may end up with tables that have many null fields.
189+
190+
## Related Java Design Patterns
191+
192+
- **Single Table Inheritance** – A strategy where a single table is used to store all classes in an
193+
inheritance hierarchy. It stores all attributes of the class and its subclasses in one table.
194+
- **Singleton Pattern** – Used when a class needs to have only one instance.
195+
196+
197+
## References and Credits
198+
199+
- **Martin Fowler** - [*Patterns of Enterprise Application Architecture*](https://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420)
200+
- **Java Persistence with Hibernate** - [Link to book](https://www.amazon.com/Java-Persistence-Hibernate-Christian-Bauer/dp/193239469X)
201+
- **Object-Relational Mapping on Wikipedia** - [Link to article](https://en.wikipedia.org/wiki/Object-relational_mapping)

table-inheritance/pom.xml

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
<parent>
7+
<groupId>com.iluwatar</groupId>
8+
<artifactId>java-design-patterns</artifactId>
9+
<version>1.26.0-SNAPSHOT</version>
10+
</parent>
11+
12+
<artifactId>table-inheritance</artifactId>
13+
14+
<dependencies>
15+
<dependency>
16+
<groupId>org.junit.jupiter</groupId>
17+
<artifactId>junit-jupiter-engine</artifactId>
18+
<version>5.7.0</version>
19+
<scope>test</scope>
20+
</dependency>
21+
<dependency>
22+
<groupId>org.projectlombok</groupId>
23+
<artifactId>lombok</artifactId>
24+
<version>1.18.24</version>
25+
<scope>provided</scope>
26+
</dependency>
27+
</dependencies>
28+
29+
30+
31+
</project>
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.iluwatar.table.inheritance;
2+
3+
import java.util.logging.Logger;
4+
5+
/**
6+
* The main entry point of the application demonstrating the use of vehicles.
7+
*
8+
* <p>The Table Inheritance pattern models a class hierarchy in a relational database by creating
9+
* separate tables for each class in the hierarchy. These tables share a common primary key, which in
10+
* subclass tables also serves as a foreign key referencing the primary key of the base class table.
11+
* This linkage maintains relationships and effectively represents the inheritance structure. This
12+
* pattern enables the organization of complex data models, particularly when subclasses have unique
13+
* properties that must be stored in distinct tables.
14+
*/
15+
16+
public class App {
17+
/**
18+
* Manages the storage and retrieval of Vehicle objects, including Cars and Trucks.
19+
*
20+
* <p>This example demonstrates the **Table Inheritance** pattern, where each vehicle type
21+
* (Car and Truck) is stored in its own separate table. The `VehicleDatabase` simulates
22+
* a simple database that manages these entities, with each subclass (Car and Truck)
23+
* being stored in its respective table.
24+
*
25+
* <p>The `VehicleDatabase` contains the following tables:
26+
* - `vehicleTable`: Stores all vehicle objects, including both `Car` and `Truck` objects.
27+
* - `carTable`: Stores only `Car` objects, with fields specific to cars.
28+
* - `truckTable`: Stores only `Truck` objects, with fields specific to trucks.
29+
*
30+
* <p>The example demonstrates:
31+
* 1. Saving instances of `Car` and `Truck` to their respective tables in the database.
32+
* 2. Retrieving vehicles (both cars and trucks) from the appropriate table based on their ID.
33+
* 3. Printing all vehicles stored in the database.
34+
* 4. Showing how to retrieve specific types of vehicles (`Car` or `Truck`) by their IDs.
35+
*
36+
* <p>In the **Table Inheritance** pattern, each subclass has its own table, making it easier
37+
* to manage specific attributes of each subclass.
38+
*
39+
* @param args command-line arguments
40+
*/
41+
42+
public static void main(String[] args) {
43+
44+
final Logger logger = Logger.getLogger(App.class.getName());
45+
46+
VehicleDatabase database = new VehicleDatabase();
47+
48+
Car car = new Car(2020, "Toyota", "Corolla", 4, 1);
49+
Truck truck = new Truck(2018, "Ford", "F-150", 60, 2);
50+
51+
database.saveVehicle(car);
52+
database.saveVehicle(truck);
53+
54+
database.printAllVehicles();
55+
56+
Vehicle vehicle = database.getVehicle(car.getId());
57+
Car retrievedCar = database.getCar(car.getId());
58+
Truck retrievedTruck = database.getTruck(truck.getId());
59+
60+
logger.info(String.format("Retrieved Vehicle: %s", vehicle));
61+
logger.info(String.format("Retrieved Car: %s", retrievedCar));
62+
logger.info(String.format("Retrieved Truck: %s", retrievedTruck));
63+
64+
}
65+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.iluwatar.table.inheritance;
2+
import lombok.Getter;
3+
/**
4+
* Represents a car with a specific number of doors.
5+
*/
6+
7+
@Getter
8+
public class Car extends Vehicle {
9+
private int numDoors;
10+
11+
/**
12+
* Constructs a Car object.
13+
*
14+
* @param year the manufacturing year
15+
* @param make the make of the car
16+
* @param model the model of the car
17+
* @param numDoors the number of doors
18+
* @param id the unique identifier for the car
19+
*/
20+
public Car(int year, String make, String model, int numDoors, int id) {
21+
super(year, make, model, id);
22+
if (numDoors <= 0) {
23+
throw new IllegalArgumentException("Number of doors must be positive.");
24+
}
25+
this.numDoors = numDoors;
26+
}
27+
28+
/**
29+
* Sets the number of doors for the car.
30+
*
31+
* @param doors the number of doors
32+
*/
33+
public void setNumDoors(int doors) {
34+
if (doors <= 0) {
35+
throw new IllegalArgumentException("Number of doors must be positive.");
36+
}
37+
this.numDoors = doors;
38+
}
39+
40+
@Override
41+
public String toString() {
42+
return "Car{"
43+
+ "id=" + getId()
44+
+ ", make='" + getMake() + '\''
45+
+ ", model='" + getModel() + '\''
46+
+ ", year=" + getYear()
47+
+ ", numberOfDoors=" + getNumDoors()
48+
+ '}';
49+
}
50+
}

0 commit comments

Comments
 (0)