Table of contents
1.
Introduction
2.
Table Per Hierarchy
3.
Hibernate Table Per Hierarchy using XML File
4.
Example of Table per class hierarchy
4.1.
Create the Persistent Classes
4.2.
Make the Persistent Class Mapping File.
4.3.
HBM File Mapping should be Included in the Configuration File.
4.4.
Make the Class for Persistent Object Storage.
4.4.1.
 
4.4.2.
Output
5.
Frequently Asked Questions
5.1.
How does TPH inheritance work?
5.2.
What does hibernate's @table mean?
5.3.
How does @DiscriminatorValue work?
5.4.
What is the purpose of Hibernate?
6.
Conclusion
Last Updated: Mar 27, 2024
Hard

Table Per Hierarchy

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello Readers! In this blog, we’ll learn about the fundamentals of Table Per Hierarchy.

Before reading about the Table Per Hierarchy, first, let’s understand Hibernate.

Hibernate (Open source object-relational mapping (ORM) program) can be defined as a framework for mapping object-oriented domain models to relational databases for web applications. Hibernate frees the developer from most routine data persistence-related programming work by mapping Java classes to database tables and from Java data types to SQL data types.

Table Per Hierarchy

In a hierarchy, data of each type is stored in a single table by TPH(Table per Hierarchy), and each row's type is determined by a discriminator column. Now you must be wondering.

What is TPH?

Table per hierarchy can be defined as the strategy of mapping the entire hierarchy to a single table. Only one Table is created, storing all the attributes and the entire class hierarchy.

We can map the hierarchy using this method with a single table, where the class is shown in the Table by an additional column (also known as the discriminator column).

Hibernate Table Per Hierarchy using XML File

 

This hierarchy consists of three classes: Employee, PartTime_Employee, and FullTime_Employee. The mapping file for this hierarchy is written below:

Here’s the code of the employee:

 

<?XML version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
 
<hibernate-mapping>  
	<class name="com.codingninjas.mypackage.Employee" table="emp121" discriminator-value="Employee">  
		<id name="id">  
		<generator class="increment"></generator>  
		</id>  
 
	<discriminator column="type" type="string"></discriminator>  
	<property name="name"></property>  
           
	<subclass name="com.codingninjas.mypackage.PartTime_Employee" discriminator-value="PartTime_Employee">  
		<property name="salary"></property>  
		<property name="bonus"></property>  
	</subclass>  
           
	<subclass name="com.codingninjas.mypackage.FullTime_Employee" discriminator-value="Fulltime_Employee">  
		<property name="pay_per_hour"></property>  
		<property name="contract_duration"></property>  
	</subclass>  
           
</class>  
           
</hibernate-mapping>  

 

The Hibernate framework adds a discriminator column that indicates the record type. It primarily serves to identify the record. The discriminator subelement of the class must be specified to do this.

The class's subclass subelement defines the subclass. In this instance, the subclasses of the Employee class are PartTime_Employee and Fulltime_Employee.

The hierarchy's table structure is depicted as follows:

hierarchy's table structure

Example of Table per class hierarchy

In this illustration, we'll create three classes and map them to one another in the employee.hbm.xml file.

Create the Persistent Classes

The permanent classes that reflect the inheritance must be created. Let's make the three classes needed for the hierarchy above

File: Employee.java

package com.codingninjas.mypackage;
public class Employee {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

 

File: FullTime_Employee.java

 

package com.codingninjas.mypackage;
public class FullTime_Employee extends Employee {
	private float pay_per_hour;
	private String contract_duration;
	public float getPay_per_hour() {
		return pay_per_hour;
	}
	public void setPay_per_hour(float pay_per_hour) {
		this.pay_per_hour = pay_per_hour;
	}
	public String getContract_duration() {
		return contract_duration;
	}
	public void setContract_duration(String contract_duration) {
		this.contract_duration = contract_duration;
	}
}

 

File: PartTime_Employee.java

 

package com.codingninjas.mypackage;
public class PartTime_Employee extends Employee {
	private float salary;
	private int bonus;
	public float getSalary() {
		return salary;
	}
	public void setSalary(float salary) {
		this.salary = salary;
	}
	public int getBonus() {
		return bonus;
	}
	public void setBonus(int bonus) {
		this.bonus = bonus;
	}
}

Make the Persistent Class Mapping File.

The hierarchy's mapping has already been covered.
 

File: employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 5.3//EN" "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">

<hibernate-mapping>
	<class name="com.codingninjas.mypackage.Employee" table="emp121" discriminator-value="emp">
		<id name="id">
			<generator class="increment"></generator>
		</id>

		<discriminator column="type" type="string"></discriminator>
		<property name="name"></property>

		<subclass name="com.codingninjas.mypackage.PartTime_Employee" discriminator-value="reg_emp">
			<property name="salary"></property>
			<property name="bonus"></property>
		</subclass>

		<subclass name="com.codingninjas.mypackage.FullTime_Employee" discriminator-value="con_emp">
			<property name="pay_per_hour"></property>
			<property name="contract_duration"></property>
		</subclass>

	</class>

</hibernate-mapping>  

HBM File Mapping should be Included in the Configuration File.

Add a mapping resource entry by opening the hibernate.cgf.xml file and doing so as follows:
 

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
         "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
         "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  

<hibernate-configuration>  

   <session-factory>  
       <property name="hbm2ddl.auto">update</property>  
       <property name="dialect">org.hibernate.dialect.MySQL</property>  
       <property name="connection.url">jdbc:mysql:://localhost:3306/database</property>  
       <property name="connection.username">root</property>  
       <property name="connection.password">password</property>  
       <property name="connection.driver_class">com.mysql.jdbc.driver,</property>  
   <mapping resource="employee.hbm.xml"/>  
   </session-factory>  

</hibernate-configuration> 

 

The hbm2ddl.auto property is intended to create database tables automatically.

Make the Class for Persistent Object Storage.

Good Resources Representation

We are only holding the employee instances in the database with this class.

 

File: StoreData.java

package com.codingninjas.mypackage;
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 StoreData {
	public static void main(String[] args) {
		StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
		Metadata metaData = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
		SessionFactory sessionFactory = metaData.getSessionFactoryBuilder().build();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		Employee employee1 = new Employee();
		employee1.setName("Siddhant Verma");
		PartTime_Employee employee2 = new PartTime_Employee();
		employee2.setName("Anshul Verma");
		employee2.setSalary(1000000);
		employee2.setBonus(50);
		FullTime_Employee employee3 = new FullTime_Employee();
		employee3.setName("Keshav Goyal");
		employee3.setPay_per_hour(1000);
		employee3.setContract_duration("20 day");
		session.persist(employee1);
		session.persist(employee2);
		session.persist(employee3);
		transaction.commit();
		session.close();
		System.out.println("Update Successful");
	}
}

 

Output

output

Frequently Asked Questions

How does TPH inheritance work?

To manage data for all entity types in an inheritance hierarchy, TPH inheritance uses a single database table.

What does hibernate's @table mean?

You can define specifics about the table that will be used to store the thing in the database using the @Table annotation.

How does @DiscriminatorValue work?

For entities of the specified type, it specifies the value of the discriminator column.

What is the purpose of Hibernate?

Hibernate is a free and open-source object-relational mapping (ORM) program that offers a framework for mapping relational databases to object-oriented domain models for web applications.

Conclusion

So that's the end of the article. Table Per Hierarchy

After reading about the Table Per Hierarchy, Are you interested in reading/exploring more? Don't worry; Coding Ninjas has you covered.

 

However, if you want to give your work an edge over the competition, you might choose to enroll in one of our premium courses.

With our Coding Ninjas Studio Guided Path, you may learn about Data Structures & Algorithms, Competitive Programming, JavaScript, System Design, and more! If you want to put your coding skills to the test, check out the mock test series on Coding Ninjas Studio and participate in the contests! But if you've only recently started your schooling and are looking for answers to issues presented by digital titans like Amazon, Microsoft, Uber, and others. In this situation, you must consider the obstaclesinterview experiences, and interview package as part of your placement preparations. If you find our blogs valuable and fascinating, please vote them up!

Good luck with your studies!

 

Live masterclass