Blog Image

Table Per Sub Class Using XmlConfiguration  

In this blog, we show you how to use Hibernate to implement "Inheritance Mapping Table Per Sub 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 Sub 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 `card` (
  `CARD_ID` int(11) NOT NULL,
  `CARD_NBR` varchar(255) DEFAULT NULL,
  `MEMBER_NM` varchar(255) DEFAULT NULL,
  `ISSUED_BANK` varchar(255) DEFAULT NULL,
  `EXPIRY_MONTH` int(11) DEFAULT NULL,
  `EXPIRY_YR` int(11) DEFAULT NULL,
  `CVV` int(11) DEFAULT NULL,
  PRIMARY KEY (`CARD_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

CREATE TABLE `credit_card` (
  `CREDIT_CARD_ID` int(11) NOT NULL,
  `AVAL_LIMIT` int(11) DEFAULT NULL,
  `CREDIT_FREE_DAYS` int(11) DEFAULT NULL,
  PRIMARY KEY (`CREDIT_CARD_ID`),
  CONSTRAINT `FKon5ld8spkv32kv9ykv5g5rkn7` FOREIGN KEY (`CREDIT_CARD_ID`) REFERENCES `card` (`CARD_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

CREATE TABLE `debit_card` (
  `DEBIT_CARD_ID` int(11) NOT NULL,
  `WITHDRAWL_LIMIT` int(11) DEFAULT NULL,
  `TRANSACTION_LIMIT` int(11) DEFAULT NULL,
  PRIMARY KEY (`DEBIT_CARD_ID`),
  CONSTRAINT `FK3gcwqqbjmmp20h9k1h9yqd1sc` FOREIGN KEY (`DEBIT_CARD_ID`) REFERENCES `card` (`CARD_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

Project Structure

Below is the maven project structure with packages and java/resource files.
Entity Classes
Card.class
package com.tpsc.entities;

public class Card {
   
    protected int cardId;  
    protected String cardNumber;  
    protected String memberName;  
    protected String issuedBank;  
    protected int expiryMonth;  
    protected int expiryYear;  
    protected int cvv;

    public int getCardId() {
        return cardId;
    }

    public void setCardId(int cardId) {
        this.cardId = cardId;
    }

    public String getCardNumber() {
        return cardNumber;
    }

    public void setCardNumber(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    public String getMemberName() {
        return memberName;
    }

    public void setMemberName(String memberName) {
        this.memberName = memberName;
    }

    public String getIssuedBank() {
        return issuedBank;
    }

    public void setIssuedBank(String issuedBank) {
        this.issuedBank = issuedBank;
    }

    public int getExpiryMonth() {
        return expiryMonth;
    }

    public void setExpiryMonth(int expiryMonth) {
        this.expiryMonth = expiryMonth;
    }

    public int getExpiryYear() {
        return expiryYear;
    }

    public void setExpiryYear(int expiryYear) {
        this.expiryYear = expiryYear;
    }

    public int getCvv() {
        return cvv;
    }

    public void setCvv(int cvv) {
        this.cvv = cvv;
    }
}
Card.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.tpsc.entities">
    <class name="Card" table="CARD">
        <id name="cardId" column="CARD_ID">
            <generator class="increment" />
        </id>
        <property name="cardNumber" column="CARD_NBR" />
        <property name="memberName" column="MEMBER_NM" />
        <property name="issuedBank" column="ISSUED_BANK" />
        <property name="expiryMonth" column="EXPIRY_MONTH" />
        <property name="expiryYear" column="EXPIRY_YR" />
        <property name="cvv" column="CVV" />
    </class>
</hibernate-mapping>
CreditCard.java
package com.tpsc.entities;

public class CreditCard extends Card {
   
    protected int availableLimit;  
    protected int creditFreeDays;

    public int getAvailableLimit() {
        return availableLimit;
    }

    public void setAvailableLimit(int availableLimit) {
        this.availableLimit = availableLimit;
    }

    public int getCreditFreeDays() {
        return creditFreeDays;
    }

    public void setCreditFreeDays(int creditFreeDays) {
        this.creditFreeDays = creditFreeDays;
    }
}
CreditCard.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.tpsc.entities">
    <joined-subclass name="CreditCard" extends="Card"
        table="CREDIT_CARD">
        <key column="CREDIT_CARD_ID" />
        <property name="availableLimit" column="AVAL_LIMIT" />
        <property name="creditFreeDays" column="CREDIT_FREE_DAYS" />
    </joined-subclass>
</hibernate-mapping>

DebitCard.java
package com.tpsc.entities;

public class DebitCard extends Card {
   
    protected int withdrawlLimit;  
    protected int transactionLimit;

    public int getWithdrawlLimit() {
        return withdrawlLimit;
    }

    public void setWithdrawlLimit(int withdrawlLimit) {
        this.withdrawlLimit = withdrawlLimit;
    }

    public int getTransactionLimit() {
        return transactionLimit;
    }

    public void setTransactionLimit(int transactionLimit) {
        this.transactionLimit = transactionLimit;
    }
}
DebitCard.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.tpsc.entities">
    <joined-subclass name="DebitCard" extends="Card" table="DEBIT_CARD">
        <key column="DEBIT_CARD_ID" />
        <property name="withdrawlLimit" column="WITHDRAWL_LIMIT" />
        <property name="transactionLimit" column="TRANSACTION_LIMIT" />
    </joined-subclass>
</hibernate-mapping>
SessionFactoryRegistry.java
package com.tpsc.util;

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

public class SessionFactoryRegistry {
    private static SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new MetadataSources(new StandardServiceRegistryBuilder().configure().build())
                    .getMetadataBuilder().build().buildSessionFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    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/inheritanceM</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/tpsc/entities/Card.hbm.xml" />
        <mapping resource="com/tpsc/entities/DebitCard.hbm.xml" />
        <mapping resource="com/tpsc/entities/CreditCard.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-Sub-Class-XmlConfiguration</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>Table-Per-Sub-Class-XmlConfiguration</name>

  <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>
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
       
        <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.tpsc.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.tpsc.entities.Card;
import com.tpsc.entities.CreditCard;
import com.tpsc.util.SessionFactoryRegistry;

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

        try {
            sessionFactory = SessionFactoryRegistry.getSessionFactory();
            session = sessionFactory.getCurrentSession();
            transaction = session.beginTransaction();

            Card card = new Card();
            card.setCardNumber("3938-3334-3445-6768");
            card.setIssuedBank("Icici");
            card.setMemberName("John");
            card.setExpiryMonth(4);
            card.setExpiryYear(2017);
            card.setCvv(242);
            session.save(card);

            CreditCard cc = new CreditCard();
            cc.setCardNumber("3940-5969-4839-5960");
            cc.setIssuedBank("Citi");
            cc.setMemberName("Mathew");
            cc.setExpiryMonth(3);
            cc.setExpiryYear(2017);
            cc.setCvv(352);
            cc.setAvailableLimit(25000);
            cc.setCreditFreeDays(45);
            session.save(cc);

            flag = true;
        } finally {
            if (transaction != null) {
                if (flag) {
                    transaction.commit();
                } else {
                    transaction.rollback();
                }
            }
            SessionFactoryRegistry.closeSessionFactory();
        }
    }
}

Please find attached the Table_Per_Sub_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:
      Indrajeet
      14-7-2018 12:57:09 PM

    Very nice and because of real time examples we are gaining more confidence . It's helping a lot. Please post Bidirectional association mapping also. Thanks you.

Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.