Table of contents
1.
Introduction
2.
TPH Using Annotations
2.1.
Illustration of Hibernate Table Per Hierarchy utilizing Annotation
2.2.
Create the Persistent Classes
2.3.
Add Project Data and Arrangement in the pom.xml Record
2.4.
Add the persistent Classes in the config
2.5.
Create the Class that Stores the Dynamic Item
2.5.1.
Output
3.
Frequently Asked Questions
3.1.
Which explanation is utilized in the table Per order?
3.2.
How might we do coordinated planning in hibernate utilizing comments?
3.3.
How would you compose one to numerous relationships in hibernation?
3.4.
What is MappedSuperclass in JPA?
3.5.
What are the three kinds of legacy planning systems depicted in JPA?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

TPH Using Annotation

Author Adya Tiwari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello Ninja, Hope you are doing well. In this article, we will be going to study TPH Using Annotation.  Also, we will implement it through coding and make it easier to understand.

tph using annotations

Let’s learn about Hibernate for now. Hibernate is a java framework that makes it easier to create Java applications that communicate with databases. It is an Object Relational Mapping (ORM) tool that is open-source and portable. Hibernate implements the JPA (Java Persistence API) requirements for data persistence. An ORM tool makes creating, manipulating and accessing data easier. It is a programming method that associates the object with the database data.

TPH Using Annotations

Table-Per-Hierarchy (TPH) uses a solitary table to store information of various kinds in the progressive system. A discriminator segment is utilized to distinguish which type each column addresses.

This approach proposes one table for the whole class inheritance hierarchy. The table incorporates a discriminator column that recognizes inheritance classes. This is a default inheritance mapping procedure in Entity Framework.

Check out Entity Framework Interview Questions to know more about it.

You want to utilize @Inheritance(strategy=InheritanceType. SINGLE_TABLE), @DiscriminatorColumn, and @DiscriminatorValue explanations for mapping the table per hierarchy procedure. In the event of a table per hierarchy, just a single table is expected to map the inheritance hierarchy.

We should see the hierarchy order:

We will take an example of a school system where school administrators hire teachers on two bases: Regular and Contract Teachers.

hierarchy order

The Teacher is the superclass for Regular_Teacher and Contract_Teacher classes.

The table design for this order is as displayed underneath:

table design

Illustration of Hibernate Table Per Hierarchy utilizing Annotation

You want to follow the accompanying moves toward making a basic model:

  • Make the persistent classes
  • Add Project Data and Arrangement in the pom.xml Record
  • Add the persistent Classes in the config
  • Create the Class that Stores the Dynamic Item
     

The info about which file to reach for each step has been highlighted below for easy access and fast processing.

Create the Persistent Classes

You want to make the persistent classes address the hierarchy. We should make the three classes in the above order:

This file is for Teacher.java
 

public class Teacher {
    private int id;
    private String Name; 

    public Teacher() {}
  
  
    public Teacher(String name) {
       this.Name = 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;
    }
   
  }
You can also try this code with Online Java Compiler
Run Code

 

Before moving to the next step, you can create similar code files for Regular_Teacher.java (Salary and Bonus) and Contract_Teacher.java(pay_per_hour and Contract _period).

code blockcontract

Add Project Data and Arrangement in the pom.xml Record

Open the pom.xml document and click the source. Presently, add the underneath code between <dependencies>....</dependencies> tag.

<dependency>  
    <groupId>org.hibernate</groupId>  
    <artifactId>hibernate-core</artifactId>  
    <version>5.3.1.Final</version>  
</dependency>  
 
<dependency>  
    <groupId>com.oracle</groupId>  
    <artifactId>ojdbc14</artifactId>  
    <version>10.2.0.4.0</version>  
</dependency> 
You can also try this code with Online Java Compiler
Run Code

Add the persistent Classes in the config

Open the hibernate.cgf.xml file, and add entries of entity classes like this:

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC  
     "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
     "http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">  
<hibernate-configuration>  
    <session-factory>  
       
    <property name="hbm2ddl.auto">update</property>
     <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
     <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
     <property name="connection.username">system</property>
     <property name="connection.password">jtp</property>
     <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
   
     <mapping class="com.codingninjas.packages.Teacher"/>  
     <mapping class="com.codingninjas.packages.Regular_Teacher"/>  
     <mapping class="com.codingninjas.packages.Contract_Teacher"/>  
     
    </session-factory>  
</hibernate-configuration> 
You can also try this code with Online Java Compiler
Run Code

Create the Class that Stores the Dynamic Item

In this class, we put away representative articles in the data set.

This is the Sample.java code file.

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 Sample {  
 
    public static void main(String args[])  
    {  
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();  
     
        SessionFactory factory=meta.getSessionFactoryBuilder().build();  
        Session session=factory.openSession();  
     
         Transaction t=session.beginTransaction();
       
            Teacher e1=new Teacher();
            e1.setName("Sahil");
           
            Regular_Teacher e2=new Regular_Teacher();
            e2.setName("Rupesh Gulia");
            e2.setSalary(60000);
            e2.setBonus(4);
           
            Contract_Teacher e3=new Contract_Teacher();
            e3.setName("Atul Chahal");
            e3.setPay_per_hour(900);
            e3.setContract_duration("20 hours");
           
            session.persist(e1);
            session.persist(e2);
            session.persist(e3);
           
            t.commit();
            session.close();
            System.out.println("success");    
    }  
} 
You can also try this code with Online Java Compiler
Run Code

 

Output

Output

Frequently Asked Questions

Which explanation is utilized in the table Per order?

You want to utilize @Inheritance(strategy=InheritanceType. SINGLE_TABLE), @DiscriminatorColumn, and @DiscriminatorValue comments for planning the table per pecking order methodology.

How might we do coordinated planning in hibernate utilizing comments?

No foreign key is made in the essential table in such a case. In this model, one worker can have one location, and one area has a place with one representative. Here, we are utilizing bidirectional affiliation.

How would you compose one to numerous relationships in hibernation?

The <many-to-one> component will be used to characterize the standard to lay out a connection between Teacher and ADDRESS substances.

What is MappedSuperclass in JPA?

Assigns a class whose planning data is applied to the substances acquired from it. A planned superclass has no different table characterized for it.

What are the three kinds of legacy planning systems depicted in JPA?

JPA Inheritance Strategies: Single table procedure, Joined procedure, and Table-per-class procedure.

Conclusion

So that's the end of the article. TPH Using Annotation

After reading about TPH Using Annotation, Are you interested in reading/exploring more themes on Table? Don't worry; Coding Ninjas has you covered.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in pygameCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems, interview experiences, and interview bundles for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass