Blog Image

Table Per Concrete Class Using XmlConfiguration  

In this blog, we show you how to use Hibernate to implement "Inheritance Mapping Table Per Concrete Class relationship by using Xml Configuration approach. This is the most common use case we often encounter in an Application Development.

Below is the example for Inheritance Mapping Table Per Concrete Class Xml Configuration approach.

Lets see Inheritance Mapping example:
Technologies used :-
1) java (1.8).
2) maven (3.5.2).
3) hibernate (5.2.12).
4) MySql (5.7.21).

Below is the table structure
Execute this query for creating tables in Database(MySql).
CREATE TABLE `parcel` (
  `parcel_no` int(11) NOT NULL,
  `descr` varchar(255) DEFAULT NULL,
  `booking_dt` datetime DEFAULT NULL,
  `cost` float DEFAULT NULL,
  PRIMARY KEY (`parcel_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

CREATE TABLE `local_parcel` (
  `parcel_no` int(11) NOT NULL,
  `descr` varchar(255) DEFAULT NULL,
  `booking_dt` datetime DEFAULT NULL,
  `cost` float DEFAULT NULL,
  `octroi` int(11) DEFAULT NULL,
  `handling_charges` int(11) DEFAULT NULL,
  PRIMARY KEY (`parcel_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

CREATE TABLE `international_parcel` (
  `parcel_no` int(11) NOT NULL,
  `descr` varchar(255) DEFAULT NULL,
  `booking_dt` datetime DEFAULT NULL,
  `cost` float DEFAULT NULL,
  `mode_of_transport` varchar(255) DEFAULT NULL,
  `special_instructions` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`parcel_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

Project Structure

Below is the maven project structure with packages and java/resource files.
Entity Classes
Parcel.java
package com.tpcc.entities;
import java.util.Date;
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;
public class Parcel {  
    protected int parcelNo;
    protected String description;
    protected Date bookingDate;
    protected float cost;

    public int getParcelNo() {
        return parcelNo;
    }

    public void setParcelNo(int parcelNo) {
        this.parcelNo = parcelNo;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getBookingDate() {
        return bookingDate;
    }

    public void setBookingDate(Date bookingDate) {
        this.bookingDate = bookingDate;
    }

    public float getCost() {
        return cost;
    }

    public void setCost(float cost) {
        this.cost = cost;
    }
}
parcel.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">;
<hibernate-mapping package="com.tpcc.entities">
    <class name="Parcel" table="parcel">
        <id name="parcelNo" column="parcel_no">
            <generator class="sequence" />
        </id>
        <property name="description" column="descr" />
        <property name="bookingDate" column="booking_dt" />
        <property name="cost" column="cost" />
    </class>
</hibernate-mapping>
LocalParcel.java
package com.tpcc.entities;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
    
public class LocalParcel extends Parcel {
    protected int octroi;
    protected int handlingCharges;

    public int getOctroi() {
        return octroi;
    }

    public void setOctroi(int octroi) {
        this.octroi = octroi;
    }

    public int getHandlingCharges() {
        return handlingCharges;
    }

    public void setHandlingCharges(int handlingCharges) {
        this.handlingCharges = handlingCharges;
    }
}
LocalParcel.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">;
<hibernate-mapping package="com.tpcc.entities">
    <union-subclass name="LocalParcel" table="local_parcel"
        extends="Parcel">
        <property name="octroi" column="octroi" />
        <property name="handlingCharges" column="handling_charges" />
    </union-subclass>
</hibernate-mapping>
InternationalParcel.java
package com.tpcc.entities;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

public class InternationalParcel extends Parcel {
    protected String modeOfTransport;
    protected String specialInstructions;

    public String getModeOfTransport() {
        return modeOfTransport;
    }

    public void setModeOfTransport(String modeOfTransport) {
        this.modeOfTransport = modeOfTransport;
    }

    public String getSpecialInstructions() {
        return specialInstructions;
    }

    public void setSpecialInstructions(String specialInstructions) {
        this.specialInstructions = specialInstructions;
    }
}
InternationalParcel,hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">;
<hibernate-mapping package="com.tpcc.entities">
    <union-subclass name="InternationalParcel" table="international_parcel"
        extends="Parcel">
        <property name="modeOfTransport" column="mode_of_transport" />
        <property name="specialInstructions" column="special_instructions" />
    </union-subclass>
</hibernate-mapping>
SessionFactoryRegistry.java
package com.tpcc.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class SessionFactoryRegistry {
    private static SessionFactory sessionFactory;

    static {
        sessionFactory= new MetadataSources(new StandardServiceRegistryBuilder().configure().build())
                .getMetadataBuilder().build().buildSessionFactory();
    }
   
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void closeSessionFactory() {
        if (sessionFactory != null) {
            sessionFactory.close();
            sessionFactory=null;
        }
    }  
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">;
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">welcome1</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/inheritance_mapping</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="current_session_context_class">thread</property>

        <mapping resource="com/tpcc/entities/Parcel.hbm.xml" />
        <mapping resource="com/tpcc/entities/LocalParcel.hbm.xml"/>
        <mapping resource="com/tpcc/entities/InternationalParcel.hbm.xml" />
       
    </session-factory>
</hibernate-configuration>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"; 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>com.otm.configure</groupId>
  <artifactId>Table-Per-concrete-Class-XmlConfiguration</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>Table-Per-concrete-Class-XmlConfiguration</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.srimanjavagroup.com</url>;

 <properties>
        <maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
        <javaee-api.version>6.0</javaee-api.version>
        <javax.servlet.version>3.1.0</javax.servlet.version>
    </properties>

  <dependencies>
        <dependency>
              <groupId>org.hibernate</groupId>
              <artifactId>hibernate-core</artifactId>
              <version>5.2.12.Final</version>
        </dependency>
        <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.34</version>
        </dependency>    
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packagi... -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
Test.java
package com.tpcc.test;

import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.tpcc.entities.LocalParcel;
import com.tpcc.entities.Parcel;
import com.tpcc.util.SessionFactoryRegistry;

public class Test {
    public static void main(String[] args) {
        SessionFactory sessionFactory = null;
        Transaction transaction = null;
        Session session = null;
        boolean flag = false;
        Parcel parcel = null;
        LocalParcel localParcel = null;

        try {
            sessionFactory = SessionFactoryRegistry.getSessionFactory();
            session = sessionFactory.getCurrentSession();
            transaction = session.beginTransaction();
           
            parcel = new Parcel();
            parcel.setDescription("Toy");
            parcel.setBookingDate(new Date());
            parcel.setCost(393.34f);
           
            session.save(parcel);
           
            localParcel = new LocalParcel();
            localParcel.setDescription("dosa");
            localParcel.setBookingDate(new Date());
            localParcel.setCost(25.3f);
            localParcel.setHandlingCharges(0);
            localParcel.setOctroi(3);
            session.save(localParcel);
           
            flag = true;
        } finally {
            if (transaction != null) {
                if (flag) {
                    transaction.commit();
                } else {
                    transaction.rollback();
                }
            }
            SessionFactoryRegistry.closeSessionFactory();
        }
    }
}

Please find attached the Table_Per_concrete_Class_XmlConfiguration.zip as an maven project as a reference. Feel free to pass your comments in the blog.

About author

User Image
Sriman

A software developer on JDK and JEE platform. I am passionate about Java technology and always an explorer and learner in new technologies in Java. I have experience on Open Source technologies like Struts, Spring, Jsf etc.. and even strong knowledge on Integration/Distributed world like Ejb, Web Services and Restful Services.

1

-Comments

Be the first person to write a comment for this Blog
  • author image
    by:
      prabina kumar
      14-7-2018 10:58:24 PM

    Thanks Mr. sriman for your explanation clarity came after go through this explanation.

Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.