Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Hibernate – Inheritance Mapping

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The inheritance hierarchy can be seen easily in the table of the database. In Hibernate we have three different strategies available for Inheritance Mapping

  • Table Per Hierarchy
  • Table Per Concrete class
  • Table Per Subclass

Hierarchy can be diagrammatically seen easily.


In this article let us see about Table Per Hierarchy using XML. It can be done using annotation as well. Here the whole hierarchy is getting mapped by a single table itself. A discriminator(differentiating) column is created in the table to identify the class. Let us take a sample between Regular worker and contract worker which are mapped from worker

Example Project

MySQL table structure

create table worker(
    workerId int auto_increment,
    workerName varchar(25),
    salary float,
    additionalBenefits int,
    pricePerHour float,
    contractPeriod varchar(25),
Primary key (workerId)

MySQL table named ‘worker’ is created with the necessary columns. By seeing the column names we can come to know that workerId and workerName should be available in the Main Worker class. salary and additionalBenefits would be for RegularWorker. pricePerHour and contractPeriod would be for ContractWorker.

Project Structure:

Project Structure


As this is the maven project, let us add pom.xml


        <!-- As we are connecting with MySQL, this is needed -->

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. Let us see worker.hbm.xml



<?xml version='1.0' encoding='UTF-8'?> 
<!DOCTYPE hibernate-mapping PUBLIC 
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN" 
      <!-- Referring to Worker bean -->
    <class name="com.gfg.hierarchy.Worker" table="worker" discriminator-value="worker"
      <id name="workerId"
          <generator class="increment"></generator
      <!-- As all columns are kept in the same table, we need to have
           a separate column named "type". It should inform about the
           type of worker. Here it can be Worker/RegularWorker/ContractWorker -->
      <discriminator column="type" type="string"></discriminator
      <property name="workerName"></property
       <!-- RegularWorker is inherited from Worker and hence it should be denoted with subclass
            and its discriminator-value="regularworker" -->
      <subclass name="com.gfg.hierarchy.RegularWorker" discriminator-value="regularworker"
        <property name="salary"></property
        <property name="additionalBenefits"></property
       <!-- ContractWorker is inherited from Worker and hence
            it should be denoted with subclass
            and its discriminator-value="contractworker" -->
      <subclass name="com.gfg.hierarchy.ContractWorker" discriminator-value="contractworker"
        <property name="pricePerHour"></property
        <property name="contractPeriod"></property

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



<?xml version='1.0' encoding='UTF-8'?> 
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "">
        <!--  As we are connecting mysql, those driver classes,
              database name, username and password are specified
              Please change the information as per your requirement -->
        <property name="">update</property
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/geeksforgeeks?serverTimezone=UTC</property>       
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
          <!--  We are going to connect worker.hbm.xml which has
              the table information about worker which is present in mysql -->
        <mapping resource="worker.hbm.xml" />

Let us see the equivalent bean classes


public class Worker {
    // Only the columns required for Worker is specified
    // As RegularWorker and ContractWorker are extended
    // from this, those required columns
    // are specified in those tables
    private int workerId;
    private String workerName;
    public int getWorkerId() {
        return workerId;
    public void setWorkerId(int workerId) {
        this.workerId = workerId;
    public String getWorkerName() {
        return workerName;
    public void setWorkerName(String workerName) {
        this.workerName = workerName;


public class RegularWorker extends Worker {
    // We are specifying only the columns
    // required for RegularWorker
    // Hence salary and additionalBenefits
    // are specified here
    private float salary;
    private int additionalBenefits;
    public float getSalary() {
        return salary;
    public void setSalary(float salary) {
        this.salary = salary;
    public int getAdditionalBenefits() {
        return additionalBenefits;
    public void setAdditionalBenefits(int additionalBenefits) {
        this.additionalBenefits = additionalBenefits;


public class ContractWorker extends Worker{
    // only the columns required for
    // ContractWorker are specified here
    private float pricePerHour; 
    private String contractPeriod;
    public float getPricePerHour() {
        return pricePerHour;
    public void setpricePerHour(float pricePerHour) {
        this.pricePerHour = pricePerHour;
    public String getContractPeriod() {
        return contractPeriod;
    public void setContractPeriod(String contractPeriod) {
        this.contractPeriod = contractPeriod;

worker.hbm.xml file is the very important key file and for “Table per hierarchy” , discriminator column is the very essential element of it.


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 
public class TablePerHierarchyWayOfStoringData { 
public static void main(String[] args) { 
    StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
    Metadata metaData=new MetadataSources(standardServiceRegistry).getMetadataBuilder().build();
    SessionFactory factory=metaData.getSessionFactoryBuilder().build();
    Session session=factory.openSession();
    Transaction transaction=session.beginTransaction(); 
    // This will indicate for  the Worker class
    Worker worker=new Worker(); 
    worker.setWorkerName("Rachel Green"); 
    // This will indicate for  the RegularWorker class
    RegularWorker regularWorker=new RegularWorker(); 
    // This will indicate for  the ContractWorker class
    ContractWorker contractWorker=new ContractWorker(); 
    contractWorker.setWorkerName("Joey Tribbiani"); 
    contractWorker.setContractPeriod("25 hours"); 
    System.out.println("success. We can see 3 records got inserted in worker table and type is the discriminator column"); 

Execution of the program and its output


We can verify the same by querying the DB data of the worker table. On execution of the above code, 3 different records are inserted. The flow is following as the Table per hierarchy and hence all the data will be inserted in a single table only, In this example use “worker” as the table name and “type” as the discriminator column, and below is the output


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

My Personal Notes arrow_drop_up
Last Updated : 24 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials