Home » Hibernate Tutorial: Table per Hierarchy Example using XML file

Hibernate Tutorial: Table per Hierarchy Example using XML file

by Online Tutorials Library

Hibernate Table Per Hierarchy using xml file

By this inheritance strategy, we can map the whole hierarchy by single table only. Here, an extra column (also known as discriminator column) is created in the table to identify the class.

Let’s understand the problem first. I want to map the whole hierarchy given below into one table of the database.

table per class hierarchy in inhertance mapping

There are three classes in this hierarchy. Employee is the super class for Regular_Employee and Contract_Employee classes. Let’s see the mapping file for this hierarchy.

In case of table per class hierarchy an discriminator column is added by the hibernate framework that specifies the type of the record. It is mainly used to distinguish the record. To specify this, discriminator subelement of class must be specified.
The subclass subelement of class, specifies the subclass. In this case, Regular_Employee and Contract_Employee are the subclasses of Employee class.

The table structure for this hierarchy is as shown below:

table per class hierarchy table


Example of Table per class hierarchy

In this example we are creating the three classes and provide mapping of these classes in the employee.hbm.xml file.

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) Create the mapping file for Persistent class

The mapping has been discussed above for the hierarchy.

File: employee.hbm.xml


3) Add mapping of hbm file in configuration file

Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:

Now the configuration file will look like this:

File: hibernate.cfg.xml

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: StoreData.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

You may also like