✅ Short Answer
Hibernate supports three main inheritance mapping strategies:
1️⃣ SINGLE_TABLE → all classes in one table.
2️⃣ JOINED → one table per class, joined by foreign keys.
3️⃣ TABLE_PER_CLASS → one table per concrete class.
🔎 Detailed Explanation
🔹 1) SINGLE_TABLE (Single Table Inheritance)
- All entities in the inheritance hierarchy share a single database table.
- A discriminator column identifies which subclass each row belongs to.
- Fastest reads → only one table to query.
- Drawback: lots of nullable columns → unused columns for some subclasses.
Usage:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
public abstract class Animal { ... }
@Entity
public class Dog extends Animal { ... }
@Entity
public class Cat extends Animal { ... }
🔹 2) JOINED (Joined Table Inheritance)
- Each class (including abstract base) has its own table.
- Subclass tables have foreign keys referencing the base table.
- Data for an entity is spread across multiple tables → requires JOINs when querying.
- Reduces null columns; better normalization.
Usage:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Animal { ... }
@Entity
public class Dog extends Animal { ... }
@Entity
public class Cat extends Animal { ... }
🔹 3) TABLE_PER_CLASS (Table per Concrete Class)
- Each concrete subclass has its own table, with all fields from the base and subclass.
- No shared base table → base class has no table if it’s abstract.
- Polymorphic queries across the hierarchy result in UNION queries → can be less efficient.
- Can cause duplicated columns across tables.
Usage:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Animal { ... }
@Entity
public class Dog extends Animal { ... }
@Entity
public class Cat extends Animal { ... }
📊 Quick Comparison Table
Strategy | Tables in DB | Speed | Null columns | Polymorphic queries |
---|---|---|---|---|
SINGLE_TABLE | 1 table | Fastest | Many possible | Simple (one table) |
JOINED | One per class, joined | Medium | Few | Joins needed |
TABLE_PER_CLASS | One per concrete class | Slowest | None | Uses UNIONs |
💡 Choosing a Strategy
✅ Use SINGLE_TABLE for performance-critical, simple hierarchies with few subclasses.
✅ Use JOINED for normalized schemas or hierarchies with many subclass-specific fields.
✅ Use TABLE_PER_CLASS when subclasses are very different, but be cautious of UNION performance.
📌 Key Takeaways
✅ Hibernate supports SINGLE_TABLE, JOINED, and TABLE_PER_CLASS inheritance strategies.
✅ Choose the strategy based on schema design, performance, and polymorphic query needs.
✅ Always use @Inheritance(strategy = …)
and optionally @DiscriminatorColumn
for SINGLE_TABLE.