Javatpoint Logo

91-9990449935

 0120-4256464

Javatpoint Logo

Hibernate Table Per Hierarchy using Annotation

In the previous page, we have mapped the inheritance hierarchy with one table only 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 following steps to create simple example:

  • Create the persistent classes
  • 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 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.


3) 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


Share this page

facebook twitter google plus pinterest tumbler

Latest 4 Tutorials