An inheritance is the way of inheriting parental properties into its sub classes or derived classes. In Hibernate, Inheritance is used among database tables. By default, Inheritance works for single class table strategy and creates a single table for its parent and sub classes. In Hibernate, we can also create multiple tables or tables per class and sub class strategy or for table join relationship.
Tables per Class Strategy by Inheritance in Detail:
In Hibernate, There are multiple strategies available by inheritance to create table and manage tables as:
- Single Table Strategy
- Table per class Strategy
- Join Table for class and sub class Strategy
To create a single table strategy, we use:
- @Inheritance(strategy=InheritanceType.SINGLE_TABLE): To define discriminator column with column name and column datatype as:
- @DiscriminatorColumn(name="VEHICLE_TYPE",discriminatorType=DiscriminatorType.STRING):To define values into for Discriminator type column in its sub classes using annotation:
- @DiscriminatorValue(“Bike”)
In this article, we are going to talk about “Table per class Strategy”. We shall use few kind of annotations that will help us to create “Table per class Strategy” by inheritance.
In this case, We will have to define the InheritanceTyp1e to TABLE_PER_CLASS strategy.
And there is no need to define any DiscriminatorType Column in the base class and DiscriminatorValues in the sub – classes. All the classes should be defined as an Entity class.
Now, Let's go with the an example that will create “TABLE_PER_CLASS” strategy using Vehicle base and its two derived classes TwoWheeler and FourWheeler classes as:
...