Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 119 ยท JPA and Hibernate

Inheritance Mapping and Embeddables

Map Java class hierarchies with JPA - @MappedSuperclass, SINGLE_TABLE, JOINED and TABLE_PER_CLASS with their SQL - plus @Embeddable value objects and element collections.

Java classes inherit from each other; database tables don't. When your domain has a Payment that can be a CardPayment or a BankTransfer, JPA has to decide how that hierarchy becomes tables: one table for everything, one per class joined by keys, or one complete table per concrete class. Each choice changes the SQL behind every insert and query, and each has a cost that only shows up when the data grows.

This lesson walks through the four options JPA gives you (@MappedSuperclass and the three @Inheritance strategies), shows the tables and SQL Hibernate produces for each, and then covers the other half of mapping rich objects: embeddables, small value objects like Address or Money that live inside an entity's row, and element collections of them. Hibernate isn't available in this sandbox, so the entity code is read-only, and the runnable programs build each table layout on H2 and run the SQL Hibernate would generate, so you can see the trade-offs for yourself. You should know entities, relationships and JPQL already.

The hierarchy used in this lesson

Every strategy maps the same three classes. A payment has an amount; a card payment adds the last four digits of the card; a bank transfer adds an IBAN:

Java
@Entity
public abstract class Payment {
    @Id @GeneratedValue
    private Long id;
    private BigDecimal amount;
}

@Entity
public class CardPayment extends Payment {
    private String cardLast4;
}

@Entity
public class BankTransfer extends Payment {
    private String iban;
}

Because Payment is an entity, you can write polymorphic queries: select p from Payment p returns a mix of CardPayment and BankTransfer objects, and a @ManyToOne Payment payment in an Order can point to either kind. That's the main reason to map inheritance at all. If you never query or reference the base type, you probably don't need entity inheritance, as the next section shows.

@MappedSuperclass: sharing fields, not tables

Very often the "inheritance" you want is just shared columns: every entity has an id, createdAt and updatedAt. Put them in a class annotated @MappedSuperclass:

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

    @Column(nullable = false, updatable = false)
    private Instant createdAt = Instant.now();

    private Instant updatedAt;

    @PreUpdate
    void touch() { updatedAt = Instant.now(); }
}

@Entity
public class Customer extends BaseEntity { private String name; }

@Entity
public class Supplier extends BaseEntity { private String company; }

A mapped superclass is not an entity. It has no table; its fields are copied into the table of every entity that extends it. You can't query it (select b from BaseEntity b fails), and no association can point to it. Mapping annotations, lifecycle callbacks like @PreUpdate and @Version are inherited, which is why base classes like this are so common.

Java What a MappedSuperclass becomes

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.

Two tables, each with its own copy of the shared columns, and both contain a row with id 1. That's fine, because nothing ever asks for "all base entities". Use @MappedSuperclass whenever you want to share code and columns, and an @Inheritance strategy only when you need to treat subclasses as one type in queries and associations.

Choosing an @Inheritance strategy

You put @Inheritance on the root entity. The three strategies:

Strategy Tables Polymorphic query Subclass columns NOT NULL?
SINGLE_TABLE (the default) one for the whole hierarchy, plus a discriminator column a plain SELECT, no joins no (other subclasses leave them empty)
JOINED one per class; subclass tables share the parent's primary key joins all subclass tables yes
TABLE_PER_CLASS one complete table per concrete class UNION ALL of all tables yes

The following sections run each one.

SINGLE_TABLE: one table and a discriminator

Java
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "kind", length = 20)    // default: DTYPE VARCHAR(31)
public abstract class Payment { ... }

@Entity
@DiscriminatorValue("CARD")                          // default: the entity name, "CardPayment"
public class CardPayment extends Payment { ... }

@Entity
@DiscriminatorValue("BANK")
public class BankTransfer extends Payment { ... }

All rows go into one payment table. Every subclass's columns are in it, and a discriminator column records which class each row belongs to. When Hibernate reads a row, it looks at the discriminator to decide which Java class to instantiate. The program below does the same thing by hand with a sealed interface and a switch:

Java SINGLE_TABLE with a discriminator

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.

A polymorphic query is one SELECT without joins, and a query for one subclass just adds WHERE kind = 'CARD'. That is why SINGLE_TABLE is the default and usually the fastest strategy.

The price is in the schema. card_last4 must be nullable, because bank transfers don't have one, so the database can't enforce "every card payment has digits" with NOT NULL. The CHECK constraint in the example restores that rule (SQLState 23513 is H2's check-violation code), but Hibernate won't generate it for you; you add it in your migration scripts. With many subclasses and many fields, the table also gets wide and mostly empty.

Hibernate can also derive the type from an expression instead of a real column with @DiscriminatorFormula("case when iban is not null then 'BANK' else 'CARD' end"), which helps when mapping a legacy table that has no type column.

JOINED: a table per class

Java
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Payment { ... }

@Entity
@PrimaryKeyJoinColumn(name = "payment_id")     // optional: name of the shared key column
public class CardPayment extends Payment { ... }

The root table holds the common columns. Each subclass table holds only its own columns, and its primary key is also a foreign key to the root. This is the most normalized design: subclass columns can be NOT NULL, and adding a subclass adds a table instead of widening one.

Every write and every read now involves several tables. Saving a CardPayment is two INSERTs. Loading one by id joins two tables. A polymorphic query must outer-join every subclass table and work out the class from which join found a row. Hibernate generates a CASE expression for that:

Java JOINED: the outer joins behind a polymorphic query

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.

With two subclasses the polymorphic query has two outer joins; with ten subclasses it has ten, on every select p from Payment p and every load of a @ManyToOne Payment. Querying a specific subclass is cheaper, since it only joins up to the root. JOINED is a good fit when subclasses have many columns of their own, when integrity constraints matter, and when most queries target a specific subclass. It is a poor fit for deep or wide hierarchies that are mostly queried polymorphically.

Hibernate doesn't need a discriminator column for JOINED, but if you declare one with @DiscriminatorColumn, it is stored in the root table, and other tools reading the database can see each row's type without joining.

TABLE_PER_CLASS: one complete table per concrete class

Java
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Payment {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)   // IDENTITY is not allowed here
    private Long id;
    ...
}

Each concrete class gets a table with all of its columns, inherited ones included. An abstract root gets no table at all. Loading a CardPayment touches one table, with no joins and no discriminator, and every column can be NOT NULL.

The cost is polymorphism. A query on Payment must combine every table with UNION ALL, and ids must be unique across all the tables, because em.find(Payment.class, 7) has to identify exactly one row. That's why GenerationType.IDENTITY (a separate counter per table) is forbidden with this strategy, and the tables share one sequence instead:

Java TABLE_PER_CLASS: a UNION ALL and a shared sequence

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.

Thanks to the shared sequence the ids are 1, 2 and 3 across both tables. Notice what the database can't do here: a foreign key from an order table can only reference one table, so an association to the abstract Payment can't have a real foreign key constraint. Use TABLE_PER_CLASS when you almost always work with concrete subclasses and rarely query the base type. In practice, it is the least used of the three.

Polymorphic queries in JPQL

Whatever the strategy, the JPQL is the same; only the generated SQL changes. A few operators help with hierarchies:

Java
// all payments, returned as CardPayment and BankTransfer instances
List<Payment> all = em.createQuery("select p from Payment p", Payment.class).getResultList();

// filter by exact class
em.createQuery("select p from Payment p where type(p) = BankTransfer", Payment.class);

// downcast to reach a subclass attribute
em.createQuery("""
    select p from Payment p
    where treat(p as CardPayment).cardLast4 = :digits
    """, Payment.class).setParameter("digits", "4242");

// a query on the subclass only sees that subclass
em.createQuery("select c from CardPayment c where c.amount > 10", CardPayment.class);

In Java, you then handle the results with pattern matching, exactly like the sealed-interface example above:

Java
String describe(Payment p) {
    return switch (p) {
        case CardPayment c -> "card ending " + c.getCardLast4();
        case BankTransfer b -> "transfer from " + b.getIban();
        default -> "unknown payment";
    };
}

Lazy associations to a polymorphic type return a proxy of the base class. If order.getPayment() is lazy, the object is a Hibernate proxy that extends Payment, so order.getPayment() instanceof CardPayment is false even when the row is a card payment. Use a fetch join, Hibernate.unproxy(payment), or a polymorphic method on Payment instead of instanceof checks on lazy references. Fetching Strategies covers proxies in detail.

Embeddables: value objects inside a row

Not every class deserves its own table. An Address has no identity of its own: two customers with the same street and city just have equal addresses. JPA calls such classes embeddables: their fields become columns of the owning entity's table.

Java
@Embeddable
public record Address(String street, String city, String postalCode) {}   // records work since Hibernate 6.2

@Embeddable
public record Money(BigDecimal amount, String currency) {}

@Entity
public class Customer {
    @Id @GeneratedValue
    private Long id;
    private String name;

    @Embedded
    private Address homeAddress;

    @Embedded
    @AttributeOverride(name = "street",     column = @Column(name = "billing_street"))
    @AttributeOverride(name = "city",       column = @Column(name = "billing_city"))
    @AttributeOverride(name = "postalCode", column = @Column(name = "billing_postal_code"))
    private Address billingAddress;

    @Embedded
    private Money creditLimit;
}

Embedding the same type twice would produce duplicate column names, so @AttributeOverride renames the second set. (Hibernate can also add a prefix automatically with @EmbeddedColumnNaming("billing_%s") in Hibernate 7.) In JPQL you navigate into embeddables with a path: where c.homeAddress.city = 'Lyon'. If all columns of an embeddable are NULL, Hibernate loads the field as null.

Embeddables are how you avoid primitive obsession: instead of String currency and BigDecimal amount scattered over twenty entities, you have one Money type with its own validation and methods, at no cost in the database.

Java Embedded value objects flattened into one row

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.

Omar's billing columns are all NULL, so his billing is null, which is exactly what Hibernate does. And because embeddables are values, comparing two addresses with equals compares their contents, which records give you for free.

@ElementCollection: collections of values

Sometimes an entity owns a collection of simple values or embeddables: a customer's phone numbers, a product's tags, an order's delivery attempts. Making each of those an entity with its own id is overkill. @ElementCollection stores them in a separate collection table keyed by the owner's id:

Java
@Entity
public class Customer {
    @Id @GeneratedValue
    private Long id;

    @ElementCollection
    @CollectionTable(name = "customer_phone", joinColumns = @JoinColumn(name = "customer_id"))
    @Column(name = "phone")
    private Set<String> phones = new HashSet<>();

    @ElementCollection
    @CollectionTable(name = "customer_address", joinColumns = @JoinColumn(name = "customer_id"))
    @OrderColumn(name = "position")              // keeps the List order in a column
    private List<Address> shippingAddresses = new ArrayList<>();
}

Element collections are lazy by default and completely owned: they are saved and deleted with the entity, they can't be shared, and they can't be queried on their own (only through the owner: join c.phones p). Their weak spot is updates. A collection row has no id, so Hibernate can't always tell which row changed. For a List without @OrderColumn (a "bag"), adding or removing one element makes Hibernate delete every row of that owner and insert them all again:

Java How Hibernate updates an element collection

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.

With three tags, removing one costs three statements as a bag and one as a set. With 500 elements, the bag costs 500. So: prefer a Set for element collections (and give the embeddable a proper equals/hashCode, which records do), use @OrderColumn when the order matters, and when the collection is large, frequently changed or needs its own queries, promote the element to a real entity with a @OneToMany instead (Entity Relationships).

Choosing a strategy

A short decision guide that matches what experienced teams do:

  1. Only sharing fields (id, audit timestamps, version)? Use @MappedSuperclass. No polymorphic queries, no extra cost.
  2. Need polymorphic queries or associations, with subclasses that add only a few columns? Use SINGLE_TABLE, and add CHECK constraints for the subclass rules in your migrations.
  3. Subclasses with many own columns, where integrity matters and most queries target one subclass? Use JOINED, and keep the hierarchy shallow.
  4. Rarely query the base type, need fully separate tables? TABLE_PER_CLASS with a sequence, accepting slow UNION queries.
  5. Not really an "is-a"? Often the best mapping is none. A Payment entity with a method enum and an embedded CardDetails, or composition with a @OneToOne, is simpler than any hierarchy.

And for value objects: a small type without identity is an @Embeddable; a small collection of them is an @ElementCollection (preferably a Set); anything bigger or independently queried becomes an entity.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. BaseEntity is annotated with @MappedSuperclass and Customer and Supplier extend it. What does select b from BaseEntity b do?

    A mapped superclass only contributes fields and mappings to its subclasses. It has no table and can't be queried or referenced by associations.
  2. 2. With SINGLE_TABLE, why can't the subclass column card_last4 be declared NOT NULL?

    All subclasses share one table, so every subclass-specific column is empty for the other subclasses. A CHECK constraint that tests the discriminator can restore the rule.
  3. 3. A JOINED hierarchy has a root and six subclasses. What does select p from Payment p usually turn into?

    JOINED stores subclass columns in their own tables, so a polymorphic query outer-joins every subclass table and uses a CASE expression to decide each row's class.
  4. 4. Why does TABLE_PER_CLASS forbid GenerationType.IDENTITY?

    Looking up a Payment by id must find exactly one row in one of the tables. Separate identity counters would give two tables a row with id 1, so the tables share a sequence instead.
  5. 5. A customer's tags are mapped as @ElementCollection List<String> without @OrderColumn. The customer has 50 tags and you remove one. Roughly what SQL runs?

    Collection rows have no id, and a bag allows duplicates, so Hibernate recreates the whole collection. A Set (or an @OrderColumn) lets it delete just the affected row.

Summary

  • @MappedSuperclass shares fields, mappings and callbacks with subclasses; it has no table and can't be queried. Use it for ids, audit columns and versions.
  • SINGLE_TABLE (default): one table plus a discriminator column; fastest queries, but subclass columns are nullable, so add CHECK constraints yourself.
  • JOINED: one table per class sharing the primary key; normalized and strict, but inserts touch several tables and polymorphic queries outer-join every subclass.
  • TABLE_PER_CLASS: a complete table per concrete class; no joins for subclass queries, but polymorphic queries need UNION ALL, ids need a shared sequence, and no foreign key can point at the base type.
  • JPQL queries look the same for every strategy; type(p) and treat(p as Sub) filter and downcast, and lazy proxies break instanceof.
  • @Embeddable value objects (records work) become columns of the owner's table; @AttributeOverride renames columns when you embed a type twice.
  • @ElementCollection stores owned values in a collection table; prefer a Set or @OrderColumn, and promote big or independently queried collections to entities.

Next: Fetching Strategies and the N+1 Problem