Menu

Inheritance Mapping Strategies

Inheritance Mapping Strategies

The Options

Relational databases have no inheritance, so Hibernate offers several ways to represent it. You choose with @Inheritance, and each option balances query speed against schema design.

Strategy

Tables

Trade-off

SINGLE_TABLEOne table for the whole hierarchyFast, but subclass columns must be nullable
JOINEDOne table per class, linked by keyClean schema, but queries need joins
TABLE_PER_CLASSOne full table per concrete classPolymorphic queries use unions and are slow

SINGLE_TABLE is the default and is the right choice in most cases.

A separate option is @MappedSuperclass. It shares fields such as id or audit columns between entities, but the parent is not an entity and cannot be queried.

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "payment_type")
public abstract class Payment {
    @Id @GeneratedValue
    private Long id;
    private double amount;
}

@Entity
@DiscriminatorValue("CARD")
public class CardPayment extends Payment {
    private String cardNumber;
}

Code Explanation:

  • All payment types are stored in one table.
  • @DiscriminatorColumn adds a column that tells Hibernate which subclass each row belongs to.
  • @DiscriminatorValue("CARD") sets the value stored for CardPayment rows.
  • cardNumber becomes nullable, since other payment types leave it empty.
  • Querying Payment returns rows of every subclass.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details