Video in progress
For inheritance, would you pick SINGLE_TABLE, JOINED or TABLE_PER_CLASS?
Most often SINGLE_TABLE: one table, no JOINs, fast polymorphic queries, but subclass columns have to be nullable. JOINED is normalized and allows NOT NULL, but every read needs a JOIN. TABLE_PER_CLASS does a UNION on polymorphic queries and is rarely chosen.
📖 Answer
Example: Payment and its subclasses CardPayment, CashPayment, TransferPayment.
SINGLE_TABLE
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Payment { ... }
@Entity
@DiscriminatorValue("CARD")
public class CardPayment extends Payment {
private String maskedPan; // NULL for the other types
}
select p from Payment p hits one table with one SELECT. The downside: you can't make the masked_pan column NOT NULL (only with a CHECK constraint), and if the subclasses multiply, the table gets wide and sparse.
JOINED: the payment table holds the common fields and card_payment holds only its own. A clean schema with correct constraints. But a polymorphic query on Payment LEFT JOINs all the subtables, and with 5-6 subclasses that's noticeable.
TABLE_PER_CLASS: each concrete class gets a full table of its own. Reading one specific type is fast, while a polymorphic query becomes a UNION ALL. It doesn't work with the IDENTITY generator.
How I choose:
- if the subclasses differ little and you mostly need a list of "all payments": SINGLE_TABLE;
- if the subclasses have many mandatory fields and data integrity matters: JOINED;
- if you almost never need a polymorphic query: maybe you don't need inheritance at all, and
@MappedSuperclassis enough.
Sign up to mark studied questions and save your progress.