In our day to day development life, Inheritance plays an important role in our applications. As we already know the advantages of inheritance in OOPS and it is also  recommended to build the interface based programming with respect to improve the re-usability.

When developing the hibernate applications, it may have multiple pojo classes. And the pojo classes may have same common properties also.

If there are common properties then in order to get re-usability, we can create a super class for the common properties. And we extend the sub class from that super class.

Example for Hibernate Inheritance Mapping :

Lets consider a scenario, we have 2 POJO classes called Cheque and Card. To save the details of Card payment or Cheque  payment in database.

Hibernte Inheritance

In both Card and Cheque classes, there can be common properties. We can separate those common properties in to a super class. Lets say Payment class and we can extend Card and Cheque both classes from Payment class.

Hibernate Inheritance 2

Hibernate Inheritance :

To achieve the inheritance in hibernate, Hibernate provides us to 3 different types of strategies.

  • Hibernate Inheritance for table per class
  • Hibernate Inheritance for table per concrete class
  • Hibernate Inheritance for table per sub class

To map the inheritance classes  to database tables we can use any one of the above strategies. There is no concept of which one is best strategy, based on our application requirement we can choose one of the above.

Recommended : Hibernate entire CRUD application

Hibernate Inheritance for Table per Class :

We can select this strategy, if we want to save the data of all classes hierarchy in to a single table of database. For this table per class strategy along with the object details, hibernate will insert a special value called discriminator to identify a pojo class objects easily in a table.

Example : Table per Class Strategy in Hibernate Inheritance

Hibernate Inheritance for Table per Concrete Class :

This hibernate inheritance strategy is selected, when there is a need to store each concrete class objects of inheritance in separate tables of database. For this strategy discriminator is optional.

Example : Table per Concrete Class in Hibernate Inheritance

Hibernate Inheritance for Table per Sub Class :

We can choose this hibernate inheritance strategy, if we want to map a super class and its sub classes to its own tables of database. A sub class table has a primary key and it is also a foreign key to get the relation with super class table.

Example : Table per Sub Class in Hibernate Inheritance (Foreign Key Relationship)