The Wayback Machine - https://web.archive.org/web/20240602124146/https://www.geeksforgeeks.org/hibernate-table-per-subclass-example-using-xml-file/
Open In App

Hibernate – Table Per Subclass Example using XML File

Last Updated : 13 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 pass information to the hibernate that applies table per subclass mapping we configure <joined-subclass> tag under <class> tag of hbm.xml file.
  • The discriminator column is optional.

Since the subclass tables have a foreign key association to the superclass table, there will not be any duplicate columns in the subclass table except one column which is required to maintain the relation between Parent and subclass tables through a foreign key.

Example for Table Per Subclass strategy (XML mapping)

Let’s suppose we have a class Employee with subclasses as P_Employee and C_Employee. Following the class diagram and relationship of these classes.

Hierarchy of Classes

Hierarchy of Classes

We have 3 tables Employee, P_Employee, and C_Employee to persist the class data. A foreign key relationship exists between the subclass tables and the superclass tables. Thus the common data is stored in the Employee table and subclass-specific fields are stored in P_Employee and C_Employee tables.

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,

    `salary` BIGINT(11) NULL DEFAULT NULL,

    PRIMARY KEY (`id`)

    CONSTRAINT `ForK_Employee` FOREIGN KEY (`id`) REFERENCES `Employee` (`id`)

)

CREATE TABLE `C_Employee` (

     `id` BIGINT(20) NOT NULL AUTO_INCREMENT,

     `hourlyrate` BIGINT(11) NULL DEFAULT NULL,

    `duration` BIGINT(11) NULL DEFAULT NULL,

    PRIMARY KEY (`id`)

    CONSTRAINT `ForK_Employee2` FOREIGN KEY (`id`) REFERENCES `Employee` (`id`)

)

Project Structure (IntelliJ IDEA) for XML mapping:

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

Below is the implementation of the Employee.java file: 

Java




package com.exploit.model;
 
public class Employee {
    private int id;
    private String name;
    private int age;
 
    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; }
}


Below is the implementation of the P_Employee.java file:

Java




package com.exploit.model;
 
public class P_Employee extends Employee {
    private double salary;
 
    public double getSalary() { return salary; }
 
    public void setSalary(double salary)
    {
        this.salary = salary;
    }
}


Below is the implementation of the C_Employee.java file: 

Java




package com.exploit.model;
 
public class C_Employee extends Employee {
    private double hourlyRate;
    private double duration;
 
    public double getDuration() { return duration; }
 
    public void setDuration(double duration)
    {
        this.duration = duration;
    }
 
    public double getHourlyRate() { return hourlyRate; }
 
    public void setHourlyRate(double hourlyRate)
    {
        this.hourlyRate = hourlyRate;
    }
}


Creating the mapping file for the Persistent class:

Below is the implementation of the employee.hbm.xml file:

XML




<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 
<hibernate-mapping package="com.exploit.model">
    <class name="Employee" table="Employee">
        <id name="id" column="Id">
            <generator class="native"></generator>
        </id>
        <property name="name" column="Name"></property>
        <property name="age" column="Age"></property>
 
        <joined-subclass name="com.exploit.model.P_Employee" table="P_Employee">
            <key column="Id"/>
            <property name="salary" column="Salary"></property>
        </joined-subclass>
 
        <joined-subclass name="com.exploit.model.C_Employee" table="C_Employee">
            <key column="Id"/>
            <property name="hourlyRate" column="HourlyRate"></property>
            <property name="duration" column="Duration"></property>
        </joined-subclass>
 
    </class>
 
</hibernate-mapping>


Adding the mapping of hbm.xml file in the hibernate configuration file:

Below is the implementation of the hibernate.cfg.xml file:

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/javainsimpleway</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
 
        <!-- JDBC connection pool (using the built-in) -->
        <property name="connection.pool_size">1</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 resource="com/exploit/mapping/employee.hbm.xml"/>
 
    </session-factory>
 
</hibernate-configuration>


Following are the dependencies used in pom.xml file:

XML




         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>TablePerSubclassXML</groupId>
    <artifactId>TablePerSubclassXML</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>TablePerSubclassXML</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>
       
    </dependencies>
</project>


Creating the class that stores the persistent object:

Below is the implementation of the Main.java file: 

Java




package com.exploit.db;
 
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;
 
public class Main {
    public static void main(String[] args)
    {
        // Get session factory using Hibernate Util class
        SessionFactory sessionFactory
            = HibernateUtil.getSessionFactory();
       
        // Get 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("ChikkoRita");
        employee.setAge(19);
 
        // Creating Permanent Employee subclass record
        P_Employee permanentEmployee = new P_Employee();
        permanentEmployee.setName("Saili.H");
        permanentEmployee.setAge(18);
        permanentEmployee.setSalary(30000);
 
        // Creating Contract Employee subclass record
        C_Employee contractEmployee = new C_Employee();
        contractEmployee.setName("KirikoChan");
        contractEmployee.setAge(19);
        contractEmployee.setHourlyRate(2000);
        contractEmployee.setDuration(8.5);
 
        // persist all the employee records
        session.persist(employee);
        session.persist(permanentEmployee);
        session.persist(contractEmployee);
 
        // Commit the transaction and close the session
        transaction.commit();
        session.close();
        System.out.println(
            "Employee records successfully persisted");
    }
}


We have defined only one hibernate mapping (hbm) file Employee.hbm.xml. Both C_Employee and P_Employee model classes are defined within one hbm.xml file. This is the usual way of mapping Table Per Subclass using XML.



Previous Article
Next Article

Similar Reads

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
Referencing Subclass objects with Subclass vs Superclass reference
Prerequisite : Inheritance In Java, all non-static methods are based on the runtime type of the underlying object rather than the type of the reference that points to that object. Therefore, it doesn't matter which type you use in the declaration of the object, the behavior will be the same. How to Refer a subclass object There are two approaches t
6 min read
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 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 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 Concrete Class 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
7 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
Hibernate Example using XML in Eclipse
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 Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XM
6 min read
Hibernate - Logging by Log4j using xml File
The process of Hibernate Logging by Log4j using an XML file deals with the ability of the computer programmer to write the log details of the file he has created by executing it permanently. The most important tools in Java language like the Log4j and Log back frameworks. These frameworks in Java language help the programmer to install and initiate
5 min read
Hibernate Mapping Set using XML
In Hibernate, if we want to map one table to another with the help of a set then we use Set mapping. Set mapping can be performed if the model class or persistent class contains a set as its element. To perform set mapping, we can use a set in the mapping file. let's see how we can configure the XML mapping file for the mapping set in hibernate. Pr
5 min read
Practice Tags :