Skip to content

Commit f635eb2

Browse files
committed
resolved comments
1 parent b5c83c0 commit f635eb2

File tree

8 files changed

+258
-136
lines changed

8 files changed

+258
-136
lines changed

table-inheritance/README.md

Lines changed: 167 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,135 @@
1-
# Table Inheritance
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+
---
215

3-
**Category:** Data Access Pattern, Structural Pattern
16+
## Also Known As
17+
- Class Table Inheritance
18+
---
419

5-
**Tags:** Decoupling, Inheritance, Polymorphism, Object Mapping, Persistence, Data Transformation
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.
627

728
---
829

9-
## Intent
10-
The **Table Inheritance** pattern models a class hierarchy in a relational database. Each class in the hierarchy is mapped to its own table, and the tables are linked through foreign keys representing the inheritance structure.
30+
## Detailed Explanation of Table Inheritance Pattern with Real-World Examples
1131

12-
This pattern is particularly useful for organizing complex data models when different subclasses have distinct properties that need to be stored in separate tables.
32+
### Real-World Example
33+
Consider a **Vehicle Management System** with a `Vehicle` superclass and subclasses like `Car` and `Truck`.
1334

14-
---
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**.
1538

16-
## Real-World Example
17-
Imagine a vehicle management system with a `Vehicle` superclass and subclasses such as `Car` and `Truck`.
18-
- The `Vehicle` table stores attributes common to all vehicles.
19-
- The subclass tables (`Car` and `Truck`) store attributes specific to each subclass.
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+
```
20119

21-
---
22120

23-
## Database Schema
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
24133

25134
### Vehicle Table
26135
| Column | Description |
@@ -44,8 +153,49 @@ Imagine a vehicle management system with a `Vehicle` superclass and subclasses s
44153

45154
---
46155

47-
## Benefits
48-
- Decouples subclasses into their own tables for easier management and scalability.
49-
- Allows for flexibility in subclass-specific attributes without altering the base table.
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
50198

51-
---
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: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,30 +11,21 @@
1111

1212
<artifactId>table-inheritance</artifactId>
1313

14-
<properties>
15-
<maven.compiler.source>17</maven.compiler.source>
16-
<maven.compiler.target>17</maven.compiler.target>
17-
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18-
</properties>
19-
2014
<dependencies>
2115
<dependency>
2216
<groupId>org.junit.jupiter</groupId>
2317
<artifactId>junit-jupiter-engine</artifactId>
2418
<version>5.7.0</version>
2519
<scope>test</scope>
2620
</dependency>
21+
<dependency>
22+
<groupId>org.projectlombok</groupId>
23+
<artifactId>lombok</artifactId>
24+
<version>1.18.24</version>
25+
<scope>provided</scope>
26+
</dependency>
2727
</dependencies>
2828

29-
<build>
30-
<plugins>
31-
<plugin>
32-
<groupId>org.apache.maven.plugins</groupId>
33-
<artifactId>maven-surefire-plugin</artifactId>
34-
<version>2.22.2</version>
35-
</plugin>
36-
</plugins>
37-
</build>
3829

3930

4031
</project>
Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,48 @@
11
package com.iluwatar.table.inheritance;
22

3+
import java.util.logging.Logger;
4+
35
/**
46
* 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.
514
*/
15+
616
public class App {
717
/**
8-
* The main method to demonstrate adding and retrieving vehicles from the database.
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.
938
*
1039
* @param args command-line arguments
1140
*/
41+
1242
public static void main(String[] args) {
43+
44+
final Logger logger = Logger.getLogger(App.class.getName());
45+
1346
VehicleDatabase database = new VehicleDatabase();
1447

1548
Car car = new Car(2020, "Toyota", "Corolla", 4, 1);
@@ -21,12 +54,12 @@ public static void main(String[] args) {
2154
database.printAllVehicles();
2255

2356
Vehicle vehicle = database.getVehicle(car.getId());
24-
System.out.println("Retrieved Vehicle: " + vehicle);
25-
2657
Car retrievedCar = database.getCar(car.getId());
27-
System.out.println("Retrieved Car: " + retrievedCar);
28-
2958
Truck retrievedTruck = database.getTruck(truck.getId());
30-
System.out.println("Retrieved Truck: " + retrievedTruck);
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+
3164
}
3265
}

table-inheritance/src/main/java/com/iluwatar/table/inheritance/Car.java

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package com.iluwatar.table.inheritance;
2-
2+
import lombok.Getter;
33
/**
44
* Represents a car with a specific number of doors.
55
*/
6+
7+
@Getter
68
public class Car extends Vehicle {
79
private int numDoors;
810

@@ -35,15 +37,6 @@ public void setNumDoors(int doors) {
3537
this.numDoors = doors;
3638
}
3739

38-
/**
39-
* Gets the number of doors for the car.
40-
*
41-
* @return the number of doors
42-
*/
43-
public int getNumDoors() {
44-
return numDoors;
45-
}
46-
4740
@Override
4841
public String toString() {
4942
return "Car{"

table-inheritance/src/main/java/com/iluwatar/table/inheritance/Truck.java

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package com.iluwatar.table.inheritance;
22

3+
import lombok.Getter;
4+
35
/**
46
* Represents a truck, a type of vehicle with a specific load capacity.
57
*/
8+
@Getter
69
public class Truck extends Vehicle {
710
private double loadCapacity;
811

@@ -35,15 +38,6 @@ public void setLoadCapacity(double capacity) {
3538
this.loadCapacity = capacity;
3639
}
3740

38-
/**
39-
* Retrieves the load capacity of the truck.
40-
*
41-
* @return the load capacity
42-
*/
43-
public double getLoadCapacity() {
44-
return loadCapacity;
45-
}
46-
4741
/**
4842
* Returns a string representation of the truck.
4943
*

0 commit comments

Comments
 (0)