Hibernate Inheritance Table per Concrete Class using JPA Annotations

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

As we mentioned earlier all the Sub Tables hold all the columns present in the  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. JPA Entity Classes

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

@AttributeOverrides:

In JPA for implementing table per concrete class inheritance we use above annotation which specifies the attributes that should be overridden from the base class to the corresponding fields and columns in the current class.

7. JPA Configuration

Below is the JPA Configuration File persistence.xml

7. Main Program

8. Output

9. Project Structure

Download JPA 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 *