in JPA, Spring

JPA tutorial – Inheritance strategy

JPA supports 3 inheritance strategies


For demonstration I will try to solve the problem of document management system where I need to store different types of documents, letter and invoice document. Here is the class diagram.


Document Class Diagram

Document Class Diagram

Single table strategy

For single table strategy JPA will create one table that has columns from all entities from the inheritance tree.

Create table SQL:

Observe the DOCUMENT_TYPE column, this is the discriminator column used by JPA to distinguish document types.


Code for all classes involved

Abstract Document Entity


@MappedSuperClass marks non entity super class.

Document Entity


In the DocumentEntity I have specified that

  • This is an entity
  • Inheritance is SINGLE_TABLE
  • Entity should be  mapped to table named DOCUMENT
  • Discriminator column is named DOCUMENT_TYPE
Invoice Document Entity

Invoice Document entity extends the Document Entity and important part is the annotation DiscriminatorValue. I will get to get in a bit.

Letter Document Entity

Letter Entity is similar to the Invoice Entity

Spring Repository and Unit Test

I will use spring repository to have CRUD support and write a unit test that will demonstrate insert and select all functionalities.

After this test is executed next SQL queries are used.

Creating entities SQL

Observe the INV and LET values, this are the values from the discriminator value specified above.

Select SQL

This is the simple select all query.

Joined strategy

To demonstrate joined strategy few changes must be done in the entities annotations. Unchanged parts are not shown in the listings.

Here is the list of changes

  • @Inheritance strategy is changed to InheritanceType.JOINED
  • @DiscriminatorColumn is removed since it does not have any effect in hibernate
  • @DiscriminatorValue is removed from Invoice and Letter
  • @Table is added

In the MySQL has 3 tables now, here is the diagram

MySQL table diagram

MySQL table diagram

Creating entities SQL

Select SQL

Select is not totally different with two left outer joins


I hope that this tutorial will help you to decide what inheritance strategy should you choose.

Write a Comment