Hibernate Table Per Hierarchy using Annotation

In the previous page, we have mapped the inheritance hierarchy with one table using xml file. Here, we are going to perform this task using annotation. You need to use @Inheritance(strategy=InheritanceType.SINGLE_TABLE), @DiscriminatorColumn and @DiscriminatorValue annotations for mapping table per hierarchy strategy.

In case of table per hierarchy, only one table is required to map the inheritance hierarchy. Here, an extra column (also known as discriminator column) is created in the table to identify the class.

Let's see the inheritance hierarchy:

table per class hierarchy using annotation

There are three classes in this hierarchy. Employee is the super class for Regular_Employee and Contract_Employee classes.

The table structure for this hierarchy is as shown below:
table per class hierarchy using annotation

Example of Hibernate Table Per Hierarchy using Annotation

You need to follow the following steps to create simple example:

  • Create the persistent classes
  • Edit pom.xml file
  • Create the configuration file
  • Create the class to store the fetch the data

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create the three classes for the above hierarchy:

File: Employee.java
File: Regular_Employee.java
File: Contract_Employee.java

2) Add project information and configuration in pom.xml file.

Open pom.xml file and click source. Now, add the below dependencies between <dependencies>....</dependencies> tag.


3) Add the persistent classes in configuration file

Open the hibernate.cgf.xml file, and add entries of entity classes like this:

The hbm2ddl.auto property is defined for creating automatic table in the database.


4) Create the class that stores the persistent object

In this class, we are simply storing the employee objects in the database.

File: StoreTest.java

Output:

output of the table per class hierarchy

Topics in Hibernate Inheritance Mapping

Table Per Hierarchy using xml file
Table Per Hierarchy using Annotation
Table Per Concrete class using xml file
Table Per Concrete class using Annotation
Table Per Subclass using xml file
Table Per Subclass using Annotation


Latest Courses