Hibernate Table Per Hierarchy using AnnotationIn 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 AnnotationYou need to follow the following steps to create simple example:
1) Create the Persistent classesYou need to create the persistent classes representing the inheritance. Let's create the three classes for the above hierarchy: File: Employee.javaFile: Regular_Employee.javaFile: Contract_Employee.java2) 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 objectIn this class, we are simply storing the employee objects in the database. File: StoreTest.javaOutput:Topics in Hibernate Inheritance MappingTable Per Hierarchy using xml fileTable 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 Next TopicTable Per Concrete Class |