VOOZH about

URL: https://www.geeksforgeeks.org/java/hibernate-inheritance-mapping/

⇱ Hibernate - Inheritance Mapping - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Hibernate - Inheritance Mapping

Last Updated : 30 Mar, 2026

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.

  • Supports mapping of parent-child class hierarchy
  • Provides multiple strategies to store inheritance in DB
  • Helps maintain clean and scalable design

Inheritance Strategies in Hibernate

Hibernate provides three strategies:

  1. Table Per Hierarchy (Single Table Strategy)
  2. Table Per Subclass (Joined Strategy)
  3. Table Per Concrete Class (Union Strategy)

Step-by-Step Project Implementation

Step 1: Create Maven Project

  • Create a Maven Project in Eclipse/IntelliJ.
  • Add Dependencies in pom.xml


Project Structure:

👁 Project Structure

Step 2: Create Database Table

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:

  • workerId, workerName: Belong to the Parent (Worker) class
  • salary, additionalBenefits: Belong to the RegularWorker class
  • pricePerHour, contractPeriod: Belong to the ContractWorker class
  • type: Used as the Discriminator column to identify class type

Step 3: Create Mapping File

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

Step 4: Create Hibernate Configuration

We are using MYSQL and hence those configurations need to be specified in hibernate.cfg.xml

hibernate.cfg.xml

Step 5: Create Entity Classes

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.

Step 6: Create Main Class

  • Creates objects of all classes
  • Saves them in DB

TablePerHierarchyWayOfStoringData.java

Execution of the program and its output

👁 Image

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.

👁 Image

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).

Comment
Article Tags: