Inheritance-Table Per Class Hierarchy

Example on hibernate table per class hierarchy:

Using Xml:

Consider we have base class named Payment and 2 derived classes like CreditCard, Cheque

hibernate-inheritance-2

Here in hibernate if we save the derived class object like (CreditCard or Cheque) then automatically Parent class object (Payment) will also be saved into the database, and in the database all the data will be stored into a single table only, which is base class table.

Here we have to specify one extra discriminator column in the database,  just to identify which derived class object we have been saved in the table along with the base class object,  if we are not using this column hibernate will throws the exception.

Example:

Required files:-

  • Payment.java (Base/Parent class)
  • CreditCard.java (Derived class)
  • Cheque.java (Derived class)
  • ClientForSave.java (for our logic)
  • Payment.hbm.xml
  • hibernate.cfg.xml

Payment.java:

CreditCard.java:

Cheque.java:

Client.java

Payment.hbm.xml:

hibernate.cfg.xml:

Notes:

  • Payment.java, CreditCard.java, Cheque.java are just pojo classes and Payment.java is the base class.
  • In this inheritance concept, mapping file is the central part, see in line number 10,  we added one new line  discriminator, after the id element just to identify which derived class object we have been saved in the table.
  • Every thing has been saved in a single table

Using Anotation :

In the above example, we have mapped the inheritance hierarchy with one table only using xml file. Here, we will see an example using annotation.

You need to use

@Inheritance(strategy=InheritanceType.SINGLE_TABLE),
@DiscriminatorColumn and
@DiscriminatorValue annotations for mapping table per hierarchy strategy.

 

Here we have a Base Class as Employee and two derived classes Permanent _Employee and Contract_Employee,

 


   

Comments are closed