Hibernate Inheritance Table per SubClass

This tutorial explains Hibernate Inheritance Table per SubClass and an implementation of the same.

1. Introduction

Java is an Object Oriented Language and supports Inheritance which is one of the most visible paradigms of Object-Relational mismatch. Object Oriented Systems can model both “is a”and “has a” relationship whereas Relational Model supports only “has a” relationship between two entities. Hibernate can help us map such Objects with relational tables.

Basically there are three ways in which we can implement Inheritance in Hibernate. We shall use one of the ways here Table per SubClass.

2. Example

Consider the below Object Model where in we have Base Class Payment and its subclasses OnlineTransfer, ChequePayment, CashPayment which are basically specific forms of Payments.

Class Diagram

Class Diagram

3. Database Table Design

In Table per Sub Class  method, we create separate table for each subclass. Each Sub Class Table such as ONLINE_PAYMENT hold a foreign key reference to PAYMENT Table. The ER Diagram for this approach would look like this.

Table Design

Table Design

As we mentioned earlier all the Sub Tables hold FOREIGN KEY reference to  PAYMENT Table.

4. Project Setup

Lets create a simple Maven project with the below pom.xml

In the above pom.xml we added dependencies for Hibernate 3.6.10, MySQL Connector 5.1.25,  Javassist and Sl4J.

5. Database Table Creation

6. Hibernate Entity Class & Hibernate Mapping File

Lets us create a Hibernate Entity  Class for Payment.java, CashPayment.java, ChequePayment.java, OnlineTransfer.java

and the Hibernate Mapping File Payment.hbm.xml as

Note that we have defined only one hibernate mapping (hbm) file Payment.hbm.xml. All the entities CashPayment,ChequePayment and Employee Entity classes are defined within the same mapping file as joined Sub Classes.

<joined-subclass> tag is used to map the subclasses of Payment. Note that we have not used the usual <class>tag to map the subclasses as it is in the hierarchy tree.

7. Hibernate Configuration

Below is the Hibernate Configuration File hibernate.cfg.xml

7. Main Program

8. Output

Console Output

Console Output

From the above Console Output we could see that irrespective of whatever class we persist all the data is inserted into PAYMENT Table.

9. Project Structure

Project Structure

Project Structure


Download Hibernate Inheritance Table per SubClass Example

I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.

Leave a Reply

Your email address will not be published. Required fields are marked *