Hibernate / Hibernate 7 Basics Interview Questions
What is the @Inheritance mapping in Hibernate 7 and what strategies are available?
Three strategies map a Java inheritance hierarchy to database tables, each with different performance and schema trade-offs.
| Strategy | Schema | Pros | Cons |
|---|---|---|---|
| SINGLE_TABLE | One table for all subclasses | Simple; best query performance | Sparse NULLs; no NOT NULL on subtype columns |
| JOINED | One table per class | Normalised; subtype constraints possible | JOIN per query; slower polymorphic queries |
| TABLE_PER_CLASS | Independent table per concrete class | No JOINs for single-type queries | Expensive UNION for polymorphic queries |
// SINGLE_TABLE (most common): @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="payment_type", discriminatorType=DiscriminatorType.STRING) public abstract class Payment { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private BigDecimal amount; } @Entity @DiscriminatorValue("CREDIT_CARD") public class CreditCardPayment extends Payment { private String cardNumber; } @Entity @DiscriminatorValue("BANK_TRANSFER") public class BankTransferPayment extends Payment { private String iban; } // JOINED: @Entity @Inheritance(strategy=InheritanceType.JOINED) public abstract class Vehicle { @Id @GeneratedValue private Long id; private String registration; } @Entity @Table(name="cars") public class Car extends Vehicle { private int doors; }
More Related questions...