Video in progress

Strong Middle 🌱 Spring

How do you choose among the SINGLE_TABLE, JOINED and TABLE_PER_CLASS strategies for entity inheritance in JPA?

SINGLE_TABLE stores everything in one table with a discriminator column: the fastest, but with many nullable columns. JOINED gives a separate table per subclass and uses JOINs: a clean schema, slower queries. TABLE_PER_CLASS produces a UNION in polymorphic queries and is rarely used.

📖 Answer

An example: Payment and the CardPayment, BankTransfer that inherit from it.

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

@Entity @DiscriminatorValue("CARD")
class CardPayment extends Payment { String maskedPan; }

@Entity @DiscriminatorValue("BANK")
class BankTransfer extends Payment { String iban; }
SINGLE_TABLE JOINED TABLE_PER_CLASS
Tables 1 parent + one per subclass one per concrete class
Polymorphic findAll a plain SELECT several JOINs UNION ALL
NOT NULL on a subclass field can't be set in the database possible possible
New subclass add a column new table new table

This is how I usually choose:

  • few subclasses with slightly different fields: SINGLE_TABLE. The fastest, and it's JPA's default. NOT NULL can be covered with CHECK (kind <> 'CARD' OR masked_pan IS NOT NULL);
  • subclasses with many specific fields and integrity matters: JOINED. But in a hierarchy with 5-6 subclasses, every polymorphic query becomes 5-6 JOINs;
  • TABLE_PER_CLASS: only if you almost never query by the parent type. It doesn't work with the IDENTITY generator.

Often the best solution is no inheritance at all: @MappedSuperclass for shared fields (no polymorphic queries), or a single entity + a type field + the specific data in a JSON column. Locking a hierarchy into the database is expensive to change later.