Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Hello and welcome, readers! We hope you are doing well. Today, in this article, we will discuss the TPS(Table Per Subclass) Using the Annotation, one ofthe inheritance mapping strategies in Hibernate. So follow the article till the end to grasp the topic completely.
So, without further ado, let’s start our discussion.
Before discussing the TPS using the annotation, you must first learn about inheritance mapping.
Inheritance Mapping
Hibernate is an open-source, lightweight Java framework that simplifies the development of the Java application to interact with the database. It is also an ORM(Object Relational Model) tool that implements the specification of JPA(Java Persistent API) for data persistence.
In Hibernate, we can map the inheritance hierarchy classes with the table of the database, known as inheritance mapping.
There are mainly three inheritance mapping strategies in Hibernate. These are as follows:
Table Per Hierarchy
Table Per Concrete Class
Table Per Subclass
Table Per Subclass
In this type of inheritance mapping strategy, tables are created as per the persistent classes, but they are treated using the primary and foreign keys. So there will not be any duplicate column in the relation.
Here, In the parent class, we need to use the @Inheritance(strategy = InheritanceType.JOINED) annotation, and for the subclasses, we need to use the @PrimaryKeyJoinColumn annotation.
Example of Table Per Subclass(TPS)
In this example, we will be creating the superclass User and its subclasses, namely Students and Teachers and showing a mapping of these classes step by step.
Create Persistent Classes
First, we will create the three persistent classes, User, Students and Teachers, representing the inheritance.
User.java
package com.codingninjas.MavenProject;
import javax.persistence.*;
@Entity
@Table(name = "users")
@Inheritance(strategy = InheritanceType.JOINED)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private int user_id;
@Column(name = "user_name")
private String user_name;
public void setUserName(String name) {
user_name = name;
}
}
You can also try this code with Online Java Compiler
After, adding the mapping the hibernate.cfg.xml would look like the below. Remember in order to connect to your own database, you need to set the properties accordingly inside the hibernate.cfg.xml.