understanding SINGLE_TABLE is key because it’s the most common (and default) inheritance strategy in JPA/Hibernate. Let’s break it down clearly:
✅ Short Answer
The SINGLE_TABLE strategy stores all entities in an inheritance hierarchy in a single database table, using a discriminator column to distinguish between subclasses.
🔎 Detailed Explanation
🔹 With SINGLE_TABLE
, you map an entire class hierarchy (base + subclasses) to one table.
🔹 The table includes columns for all fields declared in the base class and in every subclass.
🔹 Hibernate uses a discriminator column to identify which subclass a row represents:
- By default, the discriminator column is called
DTYPE
. - You can customize it with
@DiscriminatorColumn
.
🔹 Since all fields for all subclasses live in one table:
✅ Reading is fastest — no joins or unions required.
❌ Leads to many nullable columns — fields belonging to one subclass will be null for rows of other subclasses.
🧑💻 Example
Entities:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "animal_type")
public abstract class Animal {
@Id
private Long id;
private String name;
}
@Entity
public class Dog extends Animal {
private String breed;
}
@Entity
public class Cat extends Animal {
private boolean likesMilk;
}
Resulting single table:
id | name | breed | likesMilk | animal_type |
---|---|---|---|---|
1 | Fido | Beagle | NULL | Dog |
2 | Whiskers | NULL | true | Cat |
🔹 How Hibernate Uses Discriminator
- When loading rows, Hibernate reads
animal_type
(orDTYPE
by default) to decide which subclass (Dog
,Cat
, etc.) to instantiate.
📊 Advantages & Disadvantages
✅ Pros:
- Simple schema: only one table.
- Fast selects — no need for joins or unions.
- Easy to implement.
❌ Cons:
- Can result in a wide table with many nulls.
- Not normalized → bad fit if subclasses are very different in data.
📌 Key Takeaways
✅ SINGLE_TABLE stores the entire hierarchy in one table, with a discriminator column to identify subclasses.
✅ Fastest option → perfect when subclasses are similar or have few unique fields.
✅ Can waste space with many nullable columns if subclasses differ widely.