Table Per Concrete class using Annotation
In case of Table Per Concrete class, tables are created per class. So there are no nullable values in the table. Disadvantage of this approach is that duplicate columns are created in the subclass tables.
Here, we need to use @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) annotation in the parent class and @AttributeOverrides annotation in the subclasses.
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) specifies that we are using table per concrete class strategy. It should be specified in the parent class only.
@AttributeOverrides defines that parent class attributes will be overriden in this class. In table structure, parent class table columns will be added in the subclass table.
The class hierarchy is given below:
Table structure for Employee class
Table structure for Regular_Employee class
Table structure for Contract_Employee class
Example of Table per concrete class
In this example we are creating the three classes and provide mapping of these classes in the employee.hbm.xml file.
1) Create the Persistent classes
You need to create the persistent classes representing the inheritance. Let's create the three classes for the above hierarchy:File: Employee.java File: Regular_Employee.java File: Contract_Employee.java
2) Add project information and configuration in pom.xml file.
Open pom.xml file and click source. Now, add the below dependencies between <dependencies>....</dependencies> tag.
3) Add mapping of hbm file in configuration fileFile: hibernate.cfg.xml
The hbm2ddl.auto property is defined for creating automatic table in the database.
4) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.File: StoreData.java
Next TopicTable Per Subclass