Hibernate Inheritance strategy: Table Per SubClass Hierarchy

In Table Per SubClass Hierarchy there will be the number of classes equals to the number of tables in the database.
If we save the Student class object, hibernate will first save the data related to super class object into the super class related table in the database and then Student object data in Student related table in the database.
Files used in this example

Person.java (Base class)
Student.java (Derived class)
Teacher.java (Derived class)
Inheritance.java (Executing Query helper class)
TestInheritance.java (for our logic)
Person.hbm.xml
hibernate.cfg.xml

Create MySQL tables

person table
hibernate inheritance example

student table
hibernate inheritance example

teacher table
hibernate inheritance example

Person.java

 

Student.java

 

Teacher.java

 

Inheritance.java

 

TestInheritance.java

 

Person.hbm.xml:

 

hibernate.cfg.xml:

 

In the hibernate mapping file, <key/> tag is there because once we save the derived class object, hibernate will first save the base class object then derived class object. So at the time of saving the derived class object hibernate will copy the primary key value of the base class into the corresponding derived class, see in the above output 3 copied into skey column of student table and 4 copied into tkey column of the teacher table.

Once the data have been successfully saved into the database the output will be:

person table

hibernate inheritance example

student table

hibernate inheritance example

teacher table

hibernate inheritance example

That’s all. Thank your for your patience. Please do not forget to leave a comment.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.