[[entity-inheritance]]
=== Inheritance
:sourcedir: ../../../../../test/java/org/hibernate/userguide/inheritance
:extrasdir: extras/inheritance

Although relational database systems don't provide support for inheritance, Hibernate provides several strategies to leverage this object-oriented trait onto domain model entities:

MappedSuperclass:: Inheritance is implemented in the domain model only without reflecting it in the database schema. See <<entity-inheritance-mapped-superclass>>.
Single table:: The domain model class hierarchy is materialized into a single table which contains entities belonging to different class types. See <<entity-inheritance-single-table>>.
Joined table:: The base class and all the subclasses have their own database tables and fetching a subclass entity requires a join with the parent table as well. See <<entity-inheritance-joined-table>>.
Table per class:: Each subclass has its own table containing both the subclass and the base class properties. See <<entity-inheritance-table-per-class>>.

[[entity-inheritance-mapped-superclass]]
==== MappedSuperclass

In the following domain model class hierarchy, a `DebitAccount` and a `CreditAccount` share the same `Account` base class.

image:images/domain/inheritance/inheritance_class_diagram.svg[Inheritance class diagram]

When using `MappedSuperclass`, the inheritance is visible in the domain model only, and each database table contains both the base class and the subclass properties.

[[entity-inheritance-mapped-superclass-example]]
.`@MappedSuperclass` inheritance
====
[source,java]
----
include::{sourcedir}/MappedSuperclassTest.java[tags=entity-inheritance-mapped-superclass-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-mapped-superclass-example.sql[]
----
====

[NOTE]
====
Because the `@MappedSuperclass` inheritance model is not mirrored at the database level,
it's not possible to use polymorphic queries referencing the `@MappedSuperclass` when fetching persistent objects by their base class.
====

[[entity-inheritance-single-table]]
==== Single table

The single table inheritance strategy maps all subclasses to only one database table.
Each subclass declares its own persistent properties.
Version and id properties are assumed to be inherited from the root class.

[NOTE]
====
When omitting an explicit inheritance strategy (e.g. `@Inheritance`), JPA will choose the `SINGLE_TABLE` strategy by default.
====

[[entity-inheritance-single-table-example]]
.Single Table inheritance
====
[source,java]
----
include::{sourcedir}/SingleTableTest.java[tags=entity-inheritance-single-table-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-single-table-example.sql[]
----
====

Each subclass in a hierarchy must define a unique discriminator value, which is used to differentiate between rows belonging to separate subclass types.
If this is not specified, the `DTYPE` column is used as a discriminator, storing the associated subclass name.

[[entity-inheritance-single-table-persist-example]]
.Single Table inheritance discriminator column
====
[source,java]
----
include::{sourcedir}/SingleTableTest.java[tags=entity-inheritance-single-table-persist-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-single-table-persist-example.sql[]
----
====

When using polymorphic queries, only a single table is required to be scanned to fetch all associated subclass instances.

[[entity-inheritance-single-table-query-example]]
.Single Table polymorphic query
====
[source,java]
----
include::{sourcedir}/SingleTableTest.java[tags=entity-inheritance-single-table-query-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-single-table-query-example.sql[]
----
====

[IMPORTANT]
====
Among all other inheritance alternatives, the single table strategy performs the best since it requires access to one table only.
Because all subclass columns are stored in a single table, it's not possible to use NOT NULL constraints anymore, so integrity checks must be moved either into the data access layer or enforced through `CHECK` or `TRIGGER` constraints.
====

[[entity-inheritance-discriminator]]
===== Discriminator

The discriminator column contains marker values that tell the persistence layer what subclass to instantiate for a particular row.
Hibernate Core supports the following restricted set of types as discriminator column: `String`, `char`, `int`, `byte`, `short`, `boolean`(including `yes_no`, `true_false`).

Use the `@DiscriminatorColumn` to define the discriminator column as well as the discriminator type.

[NOTE]
====
The enum `DiscriminatorType` used in `javax.persistence.DiscriminatorColumn` only contains the values `STRING`, `CHAR` and `INTEGER` which means that not all Hibernate supported types are available via the `@DiscriminatorColumn` annotation.
You can also use `@DiscriminatorFormula` to express in SQL a virtual discriminator column.
This is particularly useful when the discriminator value can be extracted from one or more columns of the table.
Both `@DiscriminatorColumn` and `@DiscriminatorFormula` are to be set on the root entity (once per persisted hierarchy).

`@org.hibernate.annotations.DiscriminatorOptions` allows to optionally specify Hibernate-specific discriminator options which are not standardized in JPA.
The available options are `force` and `insert`.

The `force` attribute is useful if the table contains rows with _extra_ discriminator values that are not mapped to a persistent class.
This could, for example, occur when working with a legacy database.
If `force` is set to `true`, Hibernate will specify the allowed discriminator values in the SELECT query even when retrieving all instances of the root class.

The second option, `insert`, tells Hibernate whether or not to include the discriminator column in SQL INSERTs.
Usually, the column should be part of the INSERT statement, but if your discriminator column is also part of a mapped composite identifier you have to set this option to `false`.
====

[IMPORTANT]
====
There used to be a `@org.hibernate.annotations.ForceDiscriminator` annotation which was deprecated in version 3.6 and later removed. Use `@DiscriminatorOptions` instead.
====

[[entity-inheritance-discriminator-formula]]
====== Discriminator formula

Assuming a legacy database schema where the discriminator is based on inspecting a certain column,
we can take advantage of the Hibernate specific `@DiscriminatorFormula` annotation and map the inheritance model as follows:

[[entity-inheritance-single-table-discriminator-formula-example]]
.Single Table discriminator formula
====
[source,java]
----
include::{sourcedir}/SingleTableDiscriminatorFormulaTest.java[tags=entity-inheritance-single-table-discriminator-formula-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-single-table-discriminator-formula-example.sql[]
----
====

The `@DiscriminatorFormula` defines a custom SQL clause that can be used to identify a certain subclass type.
The `@DiscriminatorValue` defines the mapping between the result of the `@DiscriminatorFormula` and the inheritance subclass type.

[[entity-inheritance-discriminator-implicit]]
====== Implicit discriminator values

Aside from the usual discriminator values assigned to each individual subclass type, the `@DiscriminatorValue` can take two additional values:

`null`:: If the underlying discriminator column is null, the `null` discriminator mapping is going to be used.
`not null`:: If the underlying discriminator column has a not-null value that is not explicitly mapped to any entity, the `not-null` discriminator mapping used.

To understand how these two values work, consider the following entity mapping:

[[entity-inheritance-single-table-discriminator-value-example]]
.@DiscriminatorValue `null` and `not-null` entity mapping
====
[source,java]
----
include::{sourcedir}/DiscriminatorNotNullSingleTableTest.java[tags=entity-inheritance-single-table-discriminator-value-example,indent=0]
----
====

The `Account` class has a `@DiscriminatorValue( "null" )` mapping, meaning that any `account` row which does not contain any discriminator value will be mapped to an `Account` base class entity.
The `DebitAccount` and `CreditAccount` entities use explicit discriminator values.
The `OtherAccount` entity is used as a generic account type because it maps any database row whose discriminator column is not explicitly assigned to any other entity in the current inheritance tree.

To visualize how it works, consider the following example:

[[entity-inheritance-single-table-discriminator-value-persist-example]]
.@DiscriminatorValue `null` and `not-null` entity persistence
====
[source,java]
----
include::{sourcedir}/DiscriminatorNotNullSingleTableTest.java[tags=entity-inheritance-single-table-discriminator-value-persist-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-single-table-discriminator-value-persist-example.sql[]
----
====

As you can see, the `Account` entity row has a value of `NULL` in the `DTYPE` discriminator column,
while the `OtherAccount` entity was saved with a `DTYPE` column value of `other` which has not explicit mapping.

[[entity-inheritance-joined-table]]
==== Joined table

Each subclass can also be mapped to its own table.
This is also called _table-per-subclass_ mapping strategy.
An inherited state is retrieved by joining with the table of the superclass.

A discriminator column is not required for this mapping strategy.
Each subclass must, however, declare a table column holding the object identifier.

[[entity-inheritance-joined-table-example]]
.Join Table
====
[source,java]
----
include::{sourcedir}/JoinTableTest.java[tags=entity-inheritance-joined-table-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-joined-table-example.sql[]
----
====

[NOTE]
====
The primary keys of the `CreditAccount` and `DebitAccount` tables are also foreign keys to the superclass table primary key and described by the `@PrimaryKeyJoinColumns`.

The table name still defaults to the non-qualified class name.
Also, if `@PrimaryKeyJoinColumn` is not set, the primary key / foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.
====

[[entity-inheritance-joined-table-primary-key-join-column-example]]
.Join Table with `@PrimaryKeyJoinColumn`
====
[source,java]
----
include::{sourcedir}/JoinTablePrimaryKeyJoinColumnTest.java[tags=entity-inheritance-joined-table-primary-key-join-column-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-joined-table-primary-key-join-column-example.sql[]
----
====

When using polymorphic queries, the base class table must be joined with all subclass tables to fetch every associated subclass instance.

[[entity-inheritance-joined-table-query-example]]
.Join Table polymorphic query
====
[source,java]
----
include::{sourcedir}/JoinTableTest.java[tags=entity-inheritance-joined-table-query-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-joined-table-query-example.sql[]
----
====

[IMPORTANT]
====
The joined table inheritance polymorphic queries can use several JOINS which might affect performance when fetching a large number of entities.
====

[[entity-inheritance-table-per-class]]
==== Table per class

A third option is to map only the concrete classes of an inheritance hierarchy to tables.
This is called the table-per-concrete-class strategy.
Each table defines all persistent states of the class, including the inherited state.

In Hibernate, it is not necessary to explicitly map such inheritance hierarchies.
You can map each class as a separate entity root.
However, if you wish to use polymorphic associations (e.g. an association to the superclass of your hierarchy), you need to use the union subclass mapping.

[[entity-inheritance-table-per-class-example]]
.Table per class
====
[source,java]
----
include::{sourcedir}/TablePerClassTest.java[tags=entity-inheritance-table-per-class-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-table-per-class-example.sql[]
----
====

When using polymorphic queries, a UNION is required to fetch the base class table along with all subclass tables as well.

.Table per class polymorphic query
====
[source,java]
----
include::{sourcedir}/TablePerClassTest.java[tags=entity-inheritance-table-per-class-query-example,indent=0]
----

[source,sql]
----
include::{extrasdir}/entity-inheritance-table-per-class-query-example.sql[]
----
====

[IMPORTANT]
====
Polymorphic queries require multiple UNION queries, so be aware of the performance implications of a large class hierarchy.

Unfortunately, not all database systems support UNION ALL, in which case, UNION is going to be used instead of UNION ALL.

The following Hibernate dialects support UNION ALL:

- `AbstractHANADialect`
- `AbstractTransactSQLDialect`
- `CUBRIDDialect`
- `DB2Dialect`
- `H2Dialect`
- `HSQLDialect`
- `Ingres9Dialect`
- `MySQL5Dialect`
- `Oracle8iDialect`
- `Oracle9Dialect`
- `PostgreSQL81Dialect`
- `RDMSOS2200Dialect`
====

[[entity-inheritance-polymorphism]]
==== Implicit and explicit polymorphism

By default, when you query a base class entity,
the polymorphic query will fetch all subclasses belonging to the base type.

However, you can even query
*interfaces or base classes that don't belong to the JPA entity inheritance model*.

For instance, considering the following `DomainModelEntity` interface:

[[entity-inheritance-polymorphism-interface-example]]
.DomainModelEntity interface
====
[source,java]
----
include::{sourcedir}/polymorphism/DomainModelEntity.java[tags=entity-inheritance-polymorphism-interface-example,indent=0]
----
====

If we have two entity mappings, a `Book` and a `Blog`,
and the `Blog` entity is mapped with the
https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/javadocs/org/hibernate/annotations/Polymorphism.html[`@Polymorphism`] annotation
and taking the `PolymorphismType.EXPLICIT` setting:

[[entity-inheritance-polymorphism-mapping-example]]
.`@Polymorphism` entity mapping
====
[source,java]
----
include::{sourcedir}/polymorphism/ExplicitPolymorphismTest.java[tags=entity-inheritance-polymorphism-mapping-example,indent=0]
----
====

If we have the following entity objects in our system:

[[entity-inheritance-polymorphism-persist-example]]
.Domain Model entity objects
====
[source,java]
----
include::{sourcedir}/polymorphism/ExplicitPolymorphismTest.java[tags=entity-inheritance-polymorphism-persist-example,indent=0]
----
====

We can now query against the `DomainModelEntity` interface,
and Hibernate is going to fetch only the entities that are either mapped with
`@Polymorphism(type = PolymorphismType.IMPLICIT)`
or they are not annotated at all with the `@Polymorphism` annotation (implying the IMPLICIT behavior):

[[entity-inheritance-polymorphism-fetch-example]]
.Fetching Domain Model entities using non-mapped base class polymorphism
====
[source,java]
----
include::{sourcedir}/polymorphism/ExplicitPolymorphismTest.java[tags=entity-inheritance-polymorphism-fetch-example,indent=0]
----
====

Therefore, only the `Book` was fetched since the `Blog` entity was marked with the
`@Polymorphism(type = PolymorphismType.EXPLICIT)` annotation, which instructs Hibernate
to skip it when executing a polymorphic query against a non-mapped base class.