Last Updated on June 9th, 2021 at 01:16 pm
Hibernate comes with a provision to create tables and populate them as per the Java classes involved in inheritance. Hibernate offers basically three different approaches to map hierarchical classes – classes involved in inheritance with database tables. There are three types of inheritance strategy – Table per class hierarchy, Table per sub-class and Table per concrete class.
Observe, in the above hierarchy, three classes are involved where Person is the super class and Student and Teacher are subclasses with their own properties declared as instance variables.
Now the question is how many tables are required and moreover how to link the tables so that Student gets three properties of id and name(from super class), year.
Hibernate supports the three basic inheritance mapping strategies:
- table-per-class-hierarchy Only one table is created for all the classes involved in hierarchy. Here you need to maintain an extra discriminator field in table to differentiate between Student and Teacher. For more information please go through table-per-class-hierarchy
- table-per-subclass One table for each class is created. The above hierarchy gets three tables. Here, foreign key is maintained between the tables. For more information please go through table-per-subclass
- table-per-concrete-class One table for each concrete class (subclass) is created but not of super class. The above hierarchy gets two tables. As a special case, the super class can be an abstract or interface. Here, foreign key is not maintained. For more information please go through table-per-concrete-class
In addition to the above strategies, Hibernate supports a fourth, slightly different kind of polymorphism:
- implicit polymorphism: if a class or interface is used in HQL, criteria or named queries, then hibernate fetches the records from the table mapped to the class along with all the tables mapped to its sub-classes, at any hierarchy level.
That’s all about hibernate inheritance strategy.