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)

Create MySQL table

hibernate inheritance example















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.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.