Inheritance in Hibernate



Hibernate supports 3 types of Inheritance Mappings:

1. Table per class hierarchy
2. Table per sub-class hierarchy
3. Table per concrete class hierarchy



Table Per Class Hierarchy
Hey Buddy, Let’s take a ride of Table per class hierarchy consider we have base class named Area and two derived classes like Rural, Urban If we save the derived class object like Rural or Urban then automatically Area class object will also be saved into the database, and in the database all the data will be stored into a single table only, which is base class table for sure.
But here we must use one extra discriminator column in the database, just to identify
which derived class object we have saved in the table along with the base class object, if we are not using this column hibernate will throws the exception



Table Per subClass Hierarchy

Here

N number of classes = N number of tables in the database
If we save the Rural class object, then first hibernate will saves the data related to super class (Area) object into the super class related (AREA_DATA) table in the database and then Rural object data in Rural related table (RURAL_DATA) in the database, so first base class data will be saved.



Table Per Concrete Class Hierarchy

(N number of derived classes = N number of tables in the database)


Once we save the derived class object, then derived class data and base class data will be
saved in the derived class related table in the database   


For this type we need the tables for derived classes, but not for the base class 

In the mapping file we need to use one new element <union-subclass> under <class> element


In database we will have output into the Derived class related tables only, we wont have
output into the base class related rable