The Wild

Hibernate Inheritance: One Table Mapping Tips

· 6 min read · Mammals

In this article
  1. Background: Why Single Table Inheritance Exists
  2. How Single Table Mapping Works
  3. Step-by-Step Configuration
  4. When to Choose Single Table Inheritance
  5. Common Problems and How to Fix Them
  6. Comparison with Other Inheritance Strategies
  7. Frequently Asked Questions

To map an inheritance hierarchy to a single table in Hibernate, use the SINGLE_TABLE inheritance strategy (the default in JPA) with @Inheritance(strategy = InheritanceType.SINGLE_TABLE) on the root entity class. This stores all classes in the hierarchy in one database table, with a discriminator column that identifies the concrete subclass for each row.

Background: Why Single Table Inheritance Exists

Object-oriented models often use inheritance to share behavior and state, but relational databases have no native inheritance concept. Hibernate bridges this gap with three inheritance mapping strategies: single table, joined, and table-per-class. Single table is the simplest and usually the fastest for polymorphic queries because all rows live in one table—no joins are needed to retrieve mixed types.

The strategy dates back to early ORM frameworks, where performance and simplicity were paramount. It remains the default in the JPA specification because it requires the least configuration and often yields the best read performance for queries that span the hierarchy. However, it comes with trade-offs around nullability and schema design that every developer should understand before committing.

How Single Table Mapping Works

In a single-table hierarchy, Hibernate creates one table containing columns for every field in every class of the hierarchy. A special discriminator column (by default named DTYPE of type string) holds a value that identifies which subclass each row represents. When you query for a base class, Hibernate adds a WHERE DTYPE IN (...) clause to filter the appropriate types.

Consider an example with an abstract Payment class and two subclasses, CreditCardPayment and BankTransferPayment. The table might look like this:

  • id (primary key)
  • amount (from Payment)
  • card_number (from CreditCardPayment)
  • bank_account (from BankTransferPayment)
  • DTYPE (discriminator: 'CreditCard' or 'BankTransfer')

Rows for credit card payments leave bank_account null, and vice versa. Hibernate handles the mapping transparently: when you save a CreditCardPayment, it inserts a row with the appropriate discriminator value and only the relevant columns populated.

Step-by-Step Configuration

Follow these steps to set up a single-table inheritance hierarchy in Hibernate:

  1. Annotate the root entity with @Entity and @Inheritance(strategy = InheritanceType.SINGLE_TABLE). Optionally, specify a discriminator column with @DiscriminatorColumn(name = "payment_type", discriminatorType = DiscriminatorType.STRING).
  2. Define the discriminator values on each subclass using @DiscriminatorValue("CreditCard") and @DiscriminatorValue("BankTransfer"). If omitted, Hibernate uses the entity name.
  3. Map subclass-specific fields as normal @Column properties. They will be nullable in the table unless you add constraints.
  4. Ensure the root class is not final and has a no-argument constructor, as Hibernate requires for proxying.
  5. Verify the schema generated by Hibernate (or your migration tool) includes all columns and the discriminator column with a sensible length.

Here is a minimal code sketch:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "payment_type")
public abstract class Payment {
    @Id @GeneratedValue
    private Long id;
    private BigDecimal amount;
    // getters and setters
}

@Entity
@DiscriminatorValue("CreditCard")
public class CreditCardPayment extends Payment {
    private String cardNumber;
    // getters and setters
}

With this setup, Hibernate creates a single Payment table with columns id, amount, card_number, and payment_type. Queries like from Payment return all payments, while from CreditCardPayment adds a discriminator filter.

When to Choose Single Table Inheritance

Single table inheritance is a good fit when:

  • The subclasses differ by only a few fields, so the table does not become sparse with many null columns.
  • You frequently query across the entire hierarchy and want to avoid joins.
  • You need the best possible performance for polymorphic reads.
  • You can tolerate nullable columns for subclass-specific attributes.

It is less suitable when subclasses add many unique fields, because the table becomes wide and most rows have many nulls. It also complicates database-level NOT NULL constraints for subclass fields, since those columns must be nullable for rows of other types.

Common Problems and How to Fix Them

Developers often encounter these issues with single-table inheritance:

  • Null columns and data integrity: Subclass-specific columns are nullable by default. You can enforce conditional constraints with database check constraints or triggers, but Hibernate does not generate them automatically. A common workaround is to use @Column(nullable = false) only if you are certain all rows will have that column populated—which is rarely true in a mixed table.
  • Discriminator length: The default discriminator column is 31 characters. If your discriminator values are longer, specify a length with @DiscriminatorColumn(length = 50) to avoid truncation errors.
  • Lazy loading and proxies: Hibernate uses discriminator values to instantiate the correct subclass. If a discriminator value is missing or misspelled, you may get org.hibernate.WrongClassException. Always double-check @DiscriminatorValue strings.
  • Schema evolution: Adding a new subclass means adding columns to the table, which can be a heavy migration on large tables. Plan for this if the hierarchy is expected to grow.

Another frequent misconception is that single table inheritance prevents you from using foreign keys or relationships. In fact, relationships work normally: a @ManyToOne from another entity to Payment simply references the shared table.

Comparison with Other Inheritance Strategies

Hibernate offers three main strategies, each with distinct trade-offs:

  • SINGLE_TABLE: One table for the whole hierarchy. Fastest polymorphic queries, no joins, but nullable columns and a wide table.
  • JOINED: Each class gets its own table, with foreign keys linking subclass tables to the parent. Normalized schema, no nulls, but queries require joins and can be slower for deep hierarchies.
  • TABLE_PER_CLASS: Each concrete class gets a full table with all inherited fields. No discriminator, but polymorphic queries use UNION and can be inefficient; also, identity generation across tables is tricky.

Single table is often the default choice for simplicity and performance, while joined is preferred when data integrity and normalization matter more than raw speed. Table-per-class is rarely used in new projects due to its query complexity.

Frequently Asked Questions

Can I use single table inheritance with an abstract root class?

Yes. Mark the root class as abstract and annotate it with @Entity and @Inheritance. Hibernate will not create rows for the abstract class itself, but it will use it for polymorphic queries and as the parent for discriminator mapping.

What is the default discriminator column name and type?

By default, the discriminator column is named DTYPE and has type STRING (VARCHAR). You can override both with @DiscriminatorColumn on the root entity.

How do I query for a specific subclass in HQL?

Use a query like from CreditCardPayment. Hibernate automatically adds a discriminator filter so only rows of that type are returned. You can also use TYPE() in JPQL to filter by class.

Does single table inheritance support second-level caching?

Yes. Caching works normally because all data is in one table. However, be mindful that cached entities of different subclasses share the same table region, which can affect eviction strategies.

Can I add a NOT NULL constraint to a subclass-specific column?

Not directly, because rows of other subclasses would violate it. You would need a database check constraint that references the discriminator column, or handle validation in application code. Hibernate does not generate such constraints automatically.

Is single table inheritance the same as table-per-hierarchy?

Yes. “Table-per-hierarchy” is another name for the single table strategy, commonly used in ORM literature. Both terms refer to storing an entire class hierarchy in one table with a discriminator.