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:
There are three classes in this hierarchy. Employee is the super class for Regular_Employee and Contract_Employee classes.
Example of Hibernate Table Per Hierarchy using Annotation
You need to follow the following steps to create simple example:
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
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
Topics in Hibernate Inheritance MappingTable 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