91-9990449935 0120-4256464 |
Hibernate Table Per Hierarchy using AnnotationIn 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: 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 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.java File: Regular_Employee.java File: Contract_Employee.java2) Add the persistent classes in configuration file
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="hbm2ddl.auto">update</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">oracle</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping class="com.javatpoint.mypackage.Employee"/> <mapping class="com.javatpoint.mypackage.Contract_Employee"/> <mapping class="com.javatpoint.mypackage.Regular_Employee"/> </session-factory> </hibernate-configuration> The hbm2ddl.auto property is defined for creating automatic table in the database. 3) 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
|