Contents

Introduction

In JPA, an entity class may inherit from another entity class its behavior and state. The behavior and state become shared between entity classes enabling the inheritance of existing mappings -- you would only need to define mappings for a new state.

There are several types of inheritance. Two of these types -- single table inheritance and joined table inheritance -- have many similarities:

Their object model is the same.

They can be configured using either annotations or XML.

A discriminator column (a single column used for distinguishing to which class type a database row belongs) is required on the database.

The underlying database structure of the single table and joined table inheritance is, however, slightly different.

Inheritance Examples

There are two inheritance example models which you can access from SVN or download the example zip. They model an example insurance claims system.

The inheritance example model provides an example of the four inheritance types, SINGLETABLE, JOINED, TABLE_PER_CLASS, and @MappedSuperclass.

Single Table Inheritance

In the single table inheritance, the entire class hierarchy is represented by a single table. As the following example shows, the Project class and the LargeProject class map to the same PROJECT table:

The LargeProject class inherits most of its data from the Project class, with the exception of budget, which the LargeProject adds. The discriminator column (TYPE) is added to the table to distinguish between the stored instances.

You can configure the single table inheritance using either annotations or XML.

Annotations

The following example shows the mapping of the Project and LargeProject classes to the PROJECT table using annotations:

Joined Table Inheritance

In the joined table inheritance, each class shares data from the root table. In addition, each subclass defines its own table that adds its extended state. The following example shows two tables, PROJECT and L_PROJECT, as well as two classes, Project and LargeProject:

Similar to the example of the single table inheritance, the preceding joined table example demonstrates how the shared data is stored in a single table. The newly defined fields, however, are stored in a separate table.

You can configure the joined table inheritance using either annotations or XML.

Annotations

The following example shows the mapping of the Project and LargeProject classes to the PROJECT and L_PROJECT tables using annotations: