Hibernate Inheritance strategy: Table Per Class Hierarchy

I am going to give explaination and example on hibernate table per class hierarchy, consider we have base class named Person and two derived classesStudent and Teacher

If we save the derived class object like Student or Teacher then automatically Person 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 to identify which derived class object we have  saved in the table along with the base class object. This discriminator column is mandatory otherwise hibernate will throw an exception.
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 table

hibernate inheritance example

Person.java

 

Student.java

 

Teacher.java

 

Inheritance.java

 

TestInheritance.java

 

Person.hbm.xml:

 

hibernate.cfg.xml:

 

Once the data successfully saved into the database

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.