Hibernate Inheritance strategy: Table Per Concrete Class Hierarchy

In Table Per Concrete Class Hierarchy will have the number of tables in the database equals to the number of derived classes. 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. We need the tables only for derived classes. For this in the hibernate mapping file we need to use one new element <union-subclass/> under <class/> tag.
So data will be saved only in student and teacher tables.

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

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:

 

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

student table
hibernate inheritance example

teacher table
hibernate inheritance example

That’s all. Thanks 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.