In this inheritance strategy, table per class is generated. It means a separate table is generated for each POJO class involved in the hierarchy. Unlike the SINGLE_TABLE strategy, there are no nullable values present in the tables. So, to overcome the disadvantages of the SINGLE_TABLE strategy, we use TABLE_PER_CLASS.

Syntax of TABLE_PER_CLASS Inheritance

Here, Inheritance Type defines the inheritance strategy we are using.

Example of TABLE_PER_CLASS Inheritance

In this example, we are going to take three classes; i.e., Payment.java, Card.java, and Cheque.java.

The class hierarchy is given below:-

Hibernate Inheritance Table Per Class

1) Create all POJO Classes

In this step, we are going to create all the POJO classes, i.e., Payment.java, Card.java, and Cheque.java.

Payment.java

Card.java

Cheque.java

2) Create the Configuration file.

The configuration file contains the information of mapping classes and database. We are going to map all the POJO classes in the configuration file (hibernate.cfg.xml).

hibernate.cfg.xml

3) Create the main class that stores the object of POJO object

In this step, we are going to create the main class (which contains the main method) that stores the object of the POJO class.

App.java

4. OUTPUT

Hibernate Inheritance Table Per Class 1

5.  DATABASE TABLES

payment table

Hibernate Inheritance Table Per Class 2

card table

Hibernate Inheritance Table Per Class 3

cheque table

Hibernate Inheritance Table Per Class 4

Disadvantages of TABLE_PER_CLASS inheritance strategy

Following are the problems in TABLE_PER_CLASS inheritance strategy:

  • The data belongs to the superclass is scattered across many subclasses. Hence, the repeated column (amount) is present in the subclasses.
  • Any changes made to the superclass will affect the tables of subclasses.

Although this strategy is better than the SINGLE_TABLE inheritance strategy, it also has a few disadvantages. To overcome these disadvantages, we use JOINED_TABLE inheritance strategy.  

Pin It on Pinterest

Share This