Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Associations and Inheritance

Inheritance Mapping Strategies

Map Java class hierarchies to tables in Hibernate: @MappedSuperclass, SINGLE_TABLE with a discriminator, JOINED, TABLE_PER_CLASS, polymorphic queries and how to choose.

Java has inheritance, SQL does not. When CreditCard and BankTransfer both extend Payment, Hibernate has to decide how those classes are stored and how a query for "all payments" finds them. JPA defines three strategies, plus a way to share fields without sharing a table.

Real Hibernate code is read-only; the runnable programs are plain-Java stand-ins with real JDBC.

@MappedSuperclass: sharing fields only

Java
@MappedSuperclass
public abstract class BaseEntity {
    @Id @GeneratedValue
    private Long id;

    @Version
    private int version;

    private Instant createdAt = Instant.now();
}

@Entity
public class Book extends BaseEntity { ... }

A mapped superclass is not an entity: it has no table and cannot be queried or be the target of an association. Its fields simply become columns in each subclass table. Use it for ids, versions and audit columns.

The three entity strategies

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

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

@Entity
@DiscriminatorValue("BANK")
public class BankTransferPayment extends Payment {
    private String iban;
}

SINGLE_TABLE (the default)

All classes share one table with a discriminator column telling which class a row is. Subclass columns exist for all rows and are NULL where they do not apply.

  • Fastest: no joins, one table scan for polymorphic queries.
  • Weaker constraints: subclass-specific columns cannot be NOT NULL.
  • The table gets wide when there are many subclasses.

JOINED

One table for the base class and one table per subclass, linked by primary key. Reading a CreditCardPayment joins payment with credit_card_payment.

  • Normalized, with proper NOT NULL constraints.
  • Needs joins (or a left join over all subclasses for polymorphic queries), so it is slower on big hierarchies.

TABLE_PER_CLASS

Each concrete class has its own full table containing the inherited columns too. Polymorphic queries use UNION ALL.

  • No joins for queries on one concrete class.
  • Slow polymorphic queries, duplicated columns and awkward ids (cannot use IDENTITY). Rarely the right choice.
flowchart TB
    subgraph S["SINGLE_TABLE"]
      T1["payment<br/>id, amount, kind, card_masked, iban"]
    end
    subgraph J["JOINED"]
      P["payment<br/>id, amount"] --- C["credit_card_payment<br/>id, card_masked"]
      P --- B["bank_transfer_payment<br/>id, iban"]
    end
    subgraph T["TABLE_PER_CLASS"]
      C2["credit_card_payment<br/>id, amount, card_masked"]
      B2["bank_transfer_payment<br/>id, amount, iban"]
    end

One table, a table per level, or a table per concrete class.

Polymorphic queries

Java
List<Payment> all = session.createSelectionQuery("from Payment", Payment.class).getResultList();
// each element is a CreditCardPayment or a BankTransferPayment

List<CreditCardPayment> cards = session
    .createSelectionQuery("from CreditCardPayment", CreditCardPayment.class)
    .getResultList();

Querying the base class returns instances of the right subclass. Associations to the base type (@ManyToOne Payment payment) also work with SINGLE_TABLE and JOINED.

Choosing a strategy

Situation Choose
Few subclasses, few extra columns, performance matters SINGLE_TABLE
Subclasses have many own columns, strict NOT NULL needed JOINED
You only share fields, never query the base type @MappedSuperclass
You really need separate tables and rarely query polymorphically TABLE_PER_CLASS

Ask first whether inheritance is the right model; composition (an entity that holds a payment-method object) often gives simpler tables.

Stand-in: single table with a discriminator

Java Stand-in: SINGLE_TABLE and polymorphic loading

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: JOINED needs a join

Java Stand-in: JOINED tables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which strategy stores all subclasses in one table with a discriminator column?

    SINGLE_TABLE uses one table and a discriminator column to mark each row's class.
  2. 2. What is a downside of SINGLE_TABLE?

    Rows of other subclasses leave those columns empty.
  3. 3. What is a @MappedSuperclass?

    It shares mapping only; it cannot be queried or used in associations.
  4. 4. Which strategy uses UNION ALL for polymorphic queries?

    Each concrete class has its own table, so a query over the base type unions them.

Summary

  • @MappedSuperclass shares fields; the three entity strategies store a real hierarchy.
  • SINGLE_TABLE is fastest, JOINED is the most normalized, TABLE_PER_CLASS is rarely wanted.
  • Querying a base class returns the right subclass instances.
  • Consider composition before reaching for deep inheritance.
  • Here, real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

Next: Back to the Hibernate track page