![]() |
VOOZH | about |
Inheritance Mapping in Hibernate allows us to map object-oriented inheritance (Java classes) into relational database tables. It helps represent IS-A relationships between entities in a database-friendly way.
Hibernate provides three strategies:
Project Structure:
CREATE TABLE worker(
workerId INT AUTO_INCREMENT,
workerName VARCHAR(25),
salary FLOAT,
additionalBenefits INT,
pricePerHour FLOAT,
contractPeriod VARCHAR(25),
type VARCHAR(20),
PRIMARY KEY (workerId)
);
Here:
As all the columns are specified in a single table itself, then they should be distinguished by means of a discriminator column. It is specified in the hbm file.
worker.hbm.xml
We are using MYSQL and hence those configurations need to be specified in hibernate.cfg.xml
hibernate.cfg.xml
Let us see the equivalent bean classes
Worker.java
RegularWorker.java
ContractWorker.java
worker.hbm.xml file is the very important key file and for "Table per hierarchy" , discriminator column is the very essential element of it.
TablePerHierarchyWayOfStoringData.java
Execution of the program and its output
All records can be verified by querying the worker table. Since the Table Per Hierarchy strategy is used, all data is stored in a single table. The type column acts as a discriminator to identify each subclass, and 3 records are inserted accordingly.
Additionally, inheritance can be seen via Table Per Concrete class (tables are created as per class) and Table Per Subclass(tables are created as per class but related by the foreign key).