Video in progress

In a system where the entity hierarchy grows over the years, how do you choose the inheritance strategy, and how hard is it to change later?

Lots of polymorphic queries and similar subclasses: SINGLE_TABLE; large subclasses used on their own: JOINED; no polymorphic queries: @MappedSuperclass. Changing it later requires a data migration.

📖 Answer

The cost of each strategy looks different once the hierarchy grows.

SINGLE_TABLE. Great with 3 subclasses: no joins, fast polymorphic queries. After 15 subclasses, the table has 120 columns, most of them null, and you cannot put a subclass-specific NOT NULL constraint on them (you can work around it with CHECK). Every new type is an ALTER on the whole big table.

JOINED. Normalized, constraints in place. But a polymorphic query on the parent type does a LEFT JOIN to all the subclass tables. 10 subclasses means 10 joins, and that is on every find(Payment.class, id).

TABLE_PER_CLASS. A polymorphic query becomes a UNION ALL, and IDs have to be unique across all the tables (IDENTITY does not work). Rarely used in practice.

I usually ask: "In which business scenario do we need to query by the parent type?" Often the answer is none; the inheritance is there only for code reuse. In that case @MappedSuperclass (shared columns, separate tables, no polymorphic queries) is enough.

If you truly need polymorphism and expect the number of subclasses to grow, the most flexible option is often SINGLE_TABLE plus a JSON column for subclass-specific data:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "kind")
abstract class Payment {
    @JdbcTypeCode(SqlTypes.JSON)
    private Map<String, Object> attributes; // type-specific fields that are rarely queried
}

Changing the strategy means moving tables, rewiring FKs and a multi-step release with expand-contract. That is why I write this decision down in an ADR.