Video in progress
What strategies does Hibernate offer for mapping inheritance to the database?
Three. SINGLE_TABLE puts the whole hierarchy in one table, with a discriminator column marking the type. JOINED gives each class its own table, assembled with joins. TABLE_PER_CLASS gives each concrete class a full table of its own.
📖 Answer
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "payment_type")
public abstract class Payment {
@Id @GeneratedValue private Long id;
private BigDecimal amount;
}
@Entity
@DiscriminatorValue("CARD")
public class CardPayment extends Payment { private String maskedPan; }
@Entity
@DiscriminatorValue("CASH")
public class CashPayment extends Payment { private String cashier; }
A quick comparison:
| Strategy | Read speed | Downside |
|---|---|---|
SINGLE_TABLE |
fastest, no joins | subclass columns can't be NOT NULL, the table gets wide |
JOINED |
needs joins, slows down in a deep hierarchy | normalized, constraints are correct |
TABLE_PER_CLASS |
polymorphic queries use UNION, slow |
ids must be unique across all tables, IDENTITY doesn't work |
The default is SINGLE_TABLE. In practice I usually start there too: when there are few subclasses and they differ by a column or two, it's the simplest and fastest.
If you don't need polymorphic queries (select p from Payment p), @MappedSuperclass may be enough instead of inheritance.
Sign up to mark studied questions and save your progress.