Open In App

Hibernate – Table Per Concrete Class Using Annotation

Last Updated : 21 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software.

Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties.

Hibernate Inheritance Mapping

Object-oriented can model both “is a” and “has a” relationship. The relational model supports only the “has a” relationship between two entities. Hibernate helps in mapping such Objects with relational tables. There are three inheritance mapping strategies defined in the Hibernate.

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

Table per Concrete class (using Annotations)

Table per Concrete Class is one of the inheritance strategies in hibernate. If we want to keep each concrete class object of inheritance in separate tables of the database then we can proceed with the table per concrete class strategy.

In a Table per Concrete Class strategy:

  • Hibernate stores each derived class object of hierarchy in a separate table of the database.
  • Data that belongs to a parent class is scattered across a number of subclass tables, which represent concrete classes.
  • The discriminator is not required, so we can avoid discriminator-related annotations.

In this strategy, each subclass table will have the subclass-specific attributes and the attributes inherited from the parent class.

Important Annotations

Annotation 1: @Inheritance 

This annotation defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy. If the @Inheritance annotation is not specified or if no inheritance is specified for an entity class hierarchy, the SINGLE_TABLE mapping strategy is used.

Syntax: @Inheritance

@Entity
@Table("name = students")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
// Class 
public class Student {

    // Insert code here
}

Annotation 2: @AttributeOverride

The @AttributeOverride annotation is used to override the mapping of a Basic (whether explicit or default) property or field or Id property or field. This annotation may be applied to an entity that extends a mapped superclass or to an embedded field or property to override a basic mapping defined by the mapped superclass or embeddable class. If the annotation is not specified, the column is mapped the same as in the original mapping.

Syntax: @AttributeOverride

@Entity
@Table(name="students")
@AttributeOverrides({

    @AttributeOverride(name="name", column=@Column(name="NAME")),

    @AttributeOverride(name="age", column=@Column(name="AGE"))

})
// Class 
public class Student {

    // Insert code here
}

Implementation of Table Per Concrete class (Using Annotations)

In this example, we will be creating three persistence classes with Employee as the parent class and P_Employee and C_Employee as the two subclasses.

Hierarchy of Classes

We have 3 tables Employee, P_Employee, and C_Employee. The mapping of the subclass repeats the properties of the parent class.

Creating  Database Table to persist Concrete classes:

CREATE TABLE `Employee` (
        `Id` BIGINT(20) NOT NULL AUTO_INCREMENT,
       `name` VARCHAR(50) NOT NULL DEFAULT '0',
       `age` BIGINT(3) NOT NULL DEFAULT '0',
        PRIMARY KEY (`id`)
)

CREATE TABLE `P_Employee` (
       `Id` BIGINT(20) NOT NULL AUTO_INCREMENT,
      `name` VARCHAR(50) NOT NULL DEFAULT '0',
      `age` BIGINT(3) NOT NULL DEFAULT '0',
     `salary` BIGINT(11) NULL DEFAULT NULL,
     PRIMARY KEY (`id`)
)

CREATE TABLE `C_Employee` (
      `Id` BIGINT(20) NOT NULL AUTO_INCREMENT,
      `name` VARCHAR(50) NOT NULL DEFAULT '0',
      `age` BIGINT(3) NOT NULL DEFAULT '0',
      `hourlyrate` BIGINT(11) NULL DEFAULT NULL,
     `duration` BIGINT(11) NULL DEFAULT NULL,
     PRIMARY KEY (`id`)
)

The project structure (IntelliJ IDEA)  is as follows: 

Project Structure

Creating the Employee, P_Employee, and C_Employee classes for the above hierarchy:

File: Employee.java

Java




// Java Program to Demonstrate Implementation
// of Employee Class
 
package com.exploit.model;
 
// Importing required classes
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
 
// Class
@Entity
@Table(name = "Employee2")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Employee {
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
 
    // Class data member
    private int id;
    @Column(name = "name") private String name;
    @Column(name = "age") private String age;
 
    // Getter and Setters
    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; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}


File: P_Employee.java

Java




// Java Program to Demonstrate P_Employee Class
 
package com.exploit.model;
 
// Importing required classes
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
 
// Class
@Entity
@Table(name = "P_Employee")
public class P_Employee extends Employee {
 
    // Class data member
    @Column(name = "salary") private double salary;
 
    // Getter and setters
    public double getSalary() { return salary; }
    public void setSalary(double salary)
    {
        // this keyword refers to current instance itself
        this.salary = salary;
    }
}


File: C_Employee.java

Java




// Java Program to Demonstrate Implementation
// of C_Employee Class
 
package com.exploit.model;
 
// Importing required classes
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
 
// Class
@Entity
@Table(name = "C_Employee")
public class C_Employee extends Employee {
 
    // Class data members
    @Column(name = "hourlyRate") private double hourlyRate;
    @Column(name = "duration") private double duration;
 
    // getters and setters
    public double getHourlyRate() { return hourlyRate; }
    public void setHourlyRate(double hourlyRate)
    {
        // this keyword refers to current instance
        this.hourlyRate = hourlyRate;
    }
 
    public double getDuration() { return duration; }
 
    public void setDuration(double duration)
    {
        this.duration = duration;
    }
}


Creating a hibernate.cfg.xml configuration file and adding the entries of mapping resources:

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 
<hibernate-configuration>
 
    <session-factory>
 
        <!-- Database connection properties -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/exploitdb</property>
        <property name="connection.username">root</property>
        <property name="connection.password">toor</property>
 
        <!-- JDBC connection pool (using the built-in) -->
        <property name="connection.pool_size">100</property>
 
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
 
        <!-- Format the generated Sql -->
        <property name="format_sql">true</property>
 
        <!-- Dont Drop and re-create the database schema on startup,Just update
            it -->
        <property name="hbm2ddl.auto">update</property>
 
        <mapping class="com.exploit.model.Employee" />
        <mapping class="com.exploit.model.C_Employee" />
        <mapping class="com.exploit.model.P_Employee" />
 
    </session-factory>
 
</hibernate-configuration>


Following are the dependencies used in the pom.xml file:

XML




    <modelVersion>4.0.0</modelVersion>
 
    <groupId>TablePerConcreteClassAnnotation</groupId>
    <artifactId>TablePerConcreteClassAnnotation</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>TablePerConcreteClassAnnotation</name>
    <url>http://maven.apache.org</url>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.6.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.6-Final</version>
        </dependency>
 
    </dependencies>
</project>


Creating the class that stores the persistent object

File: Main.java

Java




// Java Program to Illustrate Application Class
 
package com.exploit.db;
 
// Importing required classes
import com.exploit.model.C_Employee;
import com.exploit.model.Employee;
import com.exploit.model.P_Employee;
import com.exploit.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
 
// Main class
public class Main {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Getting session factory using Hibernate Util
        // class
        SessionFactory sessionFactory
            = HibernateUtil.getSessionFactory();
 
        // Getting session from Session factory
        Session session = sessionFactory.openSession();
 
        // Begin transaction
        Transaction transaction
            = session.beginTransaction();
 
        // Creating Employee base class record
        Employee employee = new Employee();
        employee.setName("KirikoChan");
        employee.setAge(19);
 
        // Creating Permanent Employee subclass record
        P_Employee permanentEmployee = new P_Employee();
        permanentEmployee.setName("Saili.H");
        permanentEmployee.setAge(20);
        permanentEmployee.setSalary(30000);
 
        // Creating Contract Employee subclass record
        C_Employee contractEmployee = new C_Employee();
        contractEmployee.setName("ChikkoRita");
        contractEmployee.setAge(21);
        contractEmployee.setHourlyRate(2000);
        contractEmployee.setDuration(7.5);
 
        // Persisting all the employee records
        session.persist(employee);
        session.persist(permanentEmployee);
        session.persist(contractEmployee);
 
        // Commit the transaction and
        // closing the session
        transaction.commit();
        session.close();
 
        // Display message
        System.out.println(
            "Employee records successfully persisted.");
    }
}


Output:

Employee records successfully persisted.

The Main class is used to persist Employee, P_Employee, and C_Employee object instances. This is the usual way of mapping Table Per Concrete Class using Annotations.



Previous Article
Next Article

Similar Reads

Hibernate - Table Per Concrete Class using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
5 min read
Hibernate - Table Per Subclass using Annotation
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
6 min read
Hibernate - Table Per Hierarchy using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
8 min read
Hibernate - Table Per Hierarchy using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
6 min read
Hibernate - Table Per Subclass Example using XML File
In Table Per Subclass, subclass tables are mapped to the Parent class table by primary key and foreign key relationship. In a Table per Subclass strategy : For each class of hierarchy there exist a separate table in the database.While creating the database tables foreign key relationship is required between the parent table and the child table.To p
5 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Concrete class in Java
A concrete class is a class that has an implementation for all of its methods. They cannot have any unimplemented methods. It can also extend an abstract class or implement an interface as long as it implements all their methods. It is a complete class and can be instantiated. In other words, we can say that any class which is not abstract is a con
3 min read
Spring Boot - Difference Between @Service Annotation and @Repository Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. @Service Annotation In an application, the business logic resides
7 min read
Hibernate - @Embeddable and @Embedded Annotation
The @Embeddable and @Embedded annotations in Hibernate are used to map an object’s properties to columns in a database table. These annotations are used in combination to allow the properties of one class to be included as a value type in another class and then be persisted in the database as part of the containing class. OverviewThe @Embeddable an
4 min read
Hibernate - @Version Annotation with Example
@Version annotation is used to specify the version number for a specific entity. Version Number provided using @Version annotation is used to prevent concurrent modification to an entity. When an entity is being updated, the version number is also incremented. If another transaction tries to update the same entity with the older version number, an
3 min read
Hibernate - @Transient Annotation with Example
@Transient annotation in Hibernate is used to mark a property or field in an entity class as transient. This means that the field or property marked as transient should be excluded when the data persists in the database. Wherever an entity is mapped to a database table, by default all the non-transient fields and properties are persisted. There are
4 min read
Hibernate - @OrderBy Annotation with Example
@OrderBy annotation is used in Hibernate to specify the ordering of the elements in the collection valued property of an entity class. It is used to define the order of the elements which should be displayed. We can order the data within the entity using a specific parameter in ascending or descending order. Examples of @OrderBy AnnotationExample 1
4 min read
Hibernate - @GeneratedValue Annotation in JPA
@GeneratedValue annotation, the name itself suggests that it will generate something. This annotation is generally used in conjunction with @Id annotation to automatically generate unique values for primary key columns within our database tables. When creating an entity class we have to specify a primary key for that entity. For marking the field p
3 min read
Hibernate - @OneToOne Annotation
@OnetoOne annotation in Hibernate is used to create a one-to-one association between two entities. The one-to-one annotation indicates that one instance of an entity is associated with only one instance of the other entity. When we annotate a field or method with @Onetoone annotation then Hibernate will create the one-to-one relation between these
4 min read
Hibernate - @OneToMany Annotation
@OneToMany annotation in Hibernate is used to obtain one-to-many relationships between two entities. It is used to map a collection-valued association where a single instance of an entity is mapped to multiple instances of another entity. Examples of @OneToMany AnnotationExample 1: Java Code // on the below line creating an entity for Section. @Ent
4 min read
Hibernate - @MapsId Annotation
@MapsId annotation in Hibernate is used to obtain a one-to-one relationship between two entities by mapping the primary key of one entity to the foreign key of another entity. This annotation is used when we have to use a shared primary key between two entities. Examples for @MapsId AnnotationExample 1: Java Code // on the below line creating an en
3 min read
Hibernate - @ManyToOne Annotation
@ManytoOne annotation in Hibernate is used to create a many-to-one relationship between two entities. The @ManyToOne annotation indicates that the many instances of one entity can be associated with only one instance of another entity. When we annotate a field of the method with @ManyToOne annotation the Hibernate will create the many-to-one relati
4 min read
Hibernate - @ManyToMany Annotation
@ManyToMany annotation in Hibernate is used to obtain many-to-many relationships between two entities. It allows us to create a bidirectional relationship between two entities where each entity can be associated with another entity through multiple instances. Examples of @ManyToMany Annotation Example 1: Java Code // on the below line creating an e
4 min read
Hibernate - @Lob Annotation
Many times there is a scenario while storing the data in the database that we have to store images or files within our database for a specific entity. In that case, we can use @Lob annotation which will help us to map large binary objects or large character objects to a specific entity in our database. We can store images or files in our database b
3 min read
When to Use @DiscriminatorValue Annotation in Hibernate?
The @DiscriminatorColumn annotation in JPA is used to differentiate one entity from another entity class from an inheritance hierarchy. This annotation is used to provide the name of the discriminator column. It is required to specify this annotation on the root entity class only. The @DiscriminatorColumn annotation in JPA defines the discriminator
5 min read
Hibernate - @Inheritance Annotation
The @Inheritance annotation in JPA is used to specify the inheritance relation between two entities. It is used to define how the data of the entities in the hierarchy should be stored in the database. The @Inheritance annotation provides us with benefits to reduce code complexity by creating a base class and inheriting other classes from the base
6 min read
When to Use @JoinColumn Annotation in Hibernate?
The @JoinColumn annotation in Hibernate is used to specify the mapping of a foreign key column in a relationship between two entities. The @JoinColumn annotation is applied on the owning side of the association to define the foreign key column name and other attributes which are related to the join column. Examples for @JoinColumn Annotation Exampl
3 min read
Hibernate - @PrimaryKeyJoinColumn Annotation
@PrimaryKeyJoinColumn in Hibernate is used to specify the primary key of the associated entity as the foreign key of the current entity. This annotation is used to establish a one-to-one relationship between the two entities, where the primary key of one entity is considered the foreign key in another entity. Examples for @PrimaryKeyJoinColumn Anno
4 min read
Hibernate - Create Hibernate Configuration File with the Help of Plugin
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persisten
3 min read
Automatic Table Creation Using Hibernate
Hibernate is a Java framework that implements ORM(Object Relational Mapping) design pattern. It is used to map java objects into a relational database. It internally uses JDBC(Java Database Connectivity), JTA(Java Transaction API), and JNDI(Java Naming and Directory Interface). It helps to make java objects persist in the database without losing th
3 min read
Spring Data JPA - @Table Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Hibernate Configuration and Create a Table in Database
Spring Boot is used to develop REST web services and Microservices. Spring Boot reduces the configuration and setup time required for spring projects. Hibernate (Java ORM Framework) provides a framework for mapping an object-oriented domain to a relational database table like MySQL, Oracle, and PostgreSQL. Spring Boot Hibernate is used in the java
5 min read
Hidden Form Field using Annotation | Java Servlet
Hidden form field is used to store session information of a client. In this method, we create a hidden form which passes the control to the servlet whose path is given in the form action area. Using this, the information of the user is stored and passed to the location where we want to send data. The main advantage of using Hidden form field that i
4 min read
How to Capture Data using @RequestParam Annotation in Spring?
@RequestParam annotation enables spring to capture input data that may be passed as a query, form data, or any arbitrary custom data. It is used to bind a web request parameter to a method parameter. Here we are going to understand these two above lines and we will see how can we capture data using this annotation. Let's create a simple MVC applica
7 min read
Java Spring - Using @Scope Annotation to Set a POJO's Scope
In the Spring framework, when we declare a POJO instance, what we are actually creating is a template for bean definition. It means, just like a class, we can have many object instances created from a single template. When a bean definition is created, we can control not only the various dependencies and configuration values that are to be plugged
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg