Video in progress

When do you use inheritance hierarchies in JPA (SINGLE_TABLE, JOINED, TABLE_PER_CLASS), and when is composition better?

Inheritance mapping pays off when you really need polymorphic queries; SINGLE_TABLE is fast but gives nullable columns, JOINED is clean but slow because of the JOINs. Often a "type" column with @Embedded or composition with a JSON column is simpler and faster.

📖 Answer

Say Payment → CardPayment, BankTransfer, CashPayment.

Strategy Tables Reads Drawback
SINGLE_TABLE 1, with a dtype column fastest, no JOIN child-specific columns can't be NOT NULL
JOINED parent + one per child many LEFT JOINs in a polymorphic query writes are 2 INSERTs, slow on a big table
TABLE_PER_CLASS only the children a polymorphic query is a UNION ID generation is complex, I almost never use it

A typical problem on prod: with JOINED and 8 subclasses, paymentRepo.findAll(page) does 8 LEFT JOINs on every page. When the table reaches 50 million rows, this query starts taking seconds. With SINGLE_TABLE you get 40 columns, half of them NULL in every row, and data integrity lives only in the Java code: you have to restore it by hand in the database with CHECK constraints.

The composition option:

@Entity
public class Payment {
    @Id private UUID id;
    @Enumerated(EnumType.STRING) private PaymentMethod method;
    private Money amount;

    @JdbcTypeCode(SqlTypes.JSON)   // Hibernate 6
    private PaymentDetails details; // a sealed interface, with Jackson polymorphism
}

The common fields are in columns (and indexed), and the type-specific details are in JSON. The difference in behavior comes from a strategy keyed by PaymentMethod.

How I decide:

  • are there many queries across types (WHERE amount > ... for all types)?
  • will the number of subclasses grow? If it will grow a lot, each new one must not require a migration;
  • do you need to search by type-specific fields? If so, use real columns, not JSON.

A stable hierarchy with few types: SINGLE_TABLE. Type-specific data that is large and queried separately: JOINED. In most other cases: composition, not inheritance.