Hibernate inheritance:table per subclass

This is 7 of 8 parts of tutorial series

Tutorial Content:

In this tutorial,we will see how to implement inheritance in hibernate.There are 3 ways in which you can implement inheritance in hibernate.In this post,we will see one of them i.e.one table per concrete class.

Inheritance in hibernate:

Java is object oriented language and inheritance is one of main functionalities of java.Relation model can implement “is a” and “has a” relationship but hibernate provides us way to implement class hierarchy in a different ways.

Table per concrete class:

Lets say we have following class hierarchy.We have shape class as base class and Rectangle and Circle inherit from Shape class.
In  table per concrete class ,One table will be created for each concrete class..So there table will be created SHAPE,RECTANGLE and CIRCLE and subclass repeats property of parent class.

As per our class diagram,we will create three classes-Shape.java,Rectangle.java and Circle.java

1.Shape.java

This is our root class of entity class hierarchy.
Create Shape.java in src->org.arpit.javapostsforlearning.

Shape is our root class so some annotations needs to be used with root class for implementing inheritance.

@Inheritance:

For implementing inheritance in hiberante,@Inheritance annotation is used.It defines inheritance strategy to be implement for entity class hierarchy.For one table per class hierarhcy,we have used Table_Per_Class as inheritance strategy.This annotation is defined at root level or sub hierarchy level where different strategy is to be applied.

2.Rectangle.java

This is our child class.
Create Rectangle.java in src->org.arpit.javapostsforlearning.

3.Circle.java

This is our second child class.
Create Circle .java in src->org.arpit.javapostsforlearning.

4.Hiberante.cfg.xml:

Create a file named “hibernate.cfg.xml” in src folder.

5.Main Class:

Project Structure:

6.Run it:

When you run it,you will get following output.

7.SQL output:

SHAPE table in database.

Rectangle table in database

Circle table in database

Was this post helpful?

Leave a Reply

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