Pages Navigation Menu

Coding is much easier than you think

Introduction to Inheritance Mapping In Hibernate


 
Java, being a OOPs language, supports inheritance for reusability of classes. Hibernate comes with a provision to create tables and populate them as per the Java classes involved in inheritance. Suppose if we have base and derived classes, now if we save derived class object, then base class object too will be stored into the database. In order to do so, you need to choose certain mapping strategy based on your needs to save objects.
 
Hibernate supports 3 types of Inheritance Mappings to map classes involved in inheritance with database tables.
 
Example:
 

In the above hierarchy, three classes are involved where Employee is the super class and PermanentEmployee and ContractEmployee are subclasses.
 
Now the question is how many tables are required and how to link the tables so that PermanentEmployee gets three properties of empId and empName (from super class), companyName.
 

The three approaches adopted by Hibernate

  • Table-per-class-hierarchy: Only one table is created for all the classes involved in hierarchy. Here we maintain an extra discriminator column in table to differentiate between PermanentEmployee and ContractEmployee.
     
    For table-per-class hierarchy we use <subclass>in hibernate mapping file to maintain the relation between super class and subclass.
     
    Example:
     

     
  • Table-per-subclass: One table for each class is created. The above hierarchy creates three tables like following where super class primary key is subclass foreign key.
     
    For table-per-subclass we use <joined- subclass>in hibernate mapping file to maintain the relation between super class and subclass.
     
    Example:
     

     

     

     
    PID and TID are the foreign keys for EMPID of super class. This relation will be given in the mapping file.
  •  

  • Table-per-concrete-class: One table for each concrete class (subclass) is created but not of super class. Here, foreign key is not maintained.
     
    For table-per-concrete-class we use <union-subclass> in hibernate mapping file to maintain the relation between super class and subclass.
     

     

 
In our upcoming articles we shall explore each of the above mapping in detail
 

Annotation mapping

1. Table per Class Hierarchy Using Annotation
2. Table per Subclass Using Annotation
3. Table per Concrete class Using Annotation
 

XML mapping

1. Table per Class Hierarchy using XML Mapping
2. Table per Subclass using XML Mapping
3. Table per Concrete class using XML Mapping