Hibernate Inheritance Table per Concrete Class

This tutorial explains Hibernate Inheritance Table per Concrete Class 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 Concrete Class.

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 Concrete Class method, we create separate table for each concrete class. Each Concrete Class Table such as ONLINE_PAYMENT  have all the columns as present in the PAYMENT Table. The ER Diagram for this approach would look like this.

Table per concrete class

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 OnlineTransfer Entity classes are defined within the same mapping file as regular classes.

7. Hibernate Configuration

Below is the Hibernate Configuration File hibernate.cfg.xml

7. Main Program

8. Output

9. Project Structure

Download Hibernate Inheritance Table per Concrete Class 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 *