Hibernate Inheritance Using XML
Hibernate Inheritance Using XML
Suppose if we have base and derived classes, now if we save derived(sub) class object, base class
object will also be stored into the database.
But the thing is we must specify in what table we need to save which object data. Hibernate
supports 3 types of Inheritance Mappings:
Here is the explanation and one example on hibernate table per class hierarchy, consider we have
base class named Payment and 2 derived classes like CreditCard, Cheque.
If we save the derived class object like CreditCard or Cheque then automatically Payment class
object 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 for sure.
But here we must use 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, see this example so that you will get one idea on this
concept.
Notes:
Payment.java, CreditCard.java, Cheque.java are just pojo classes nothing to explain, but see in
CreditCard.java, Cheque.java i have inherited the Payment.java.
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 (see the oracle console once)
This is also just like previous example, but some changes are there, in table per class hierarchy all the
data was saved in a single table but here,
If we save the CreditCard class object, then first hibernate will saves the data related to super class
object into the super class related table in the database and then CreditCard object data in
CreditCard related table in the database, so first base class data will be saved
Notes:
In the mapping file, <key –> element is because, once we save the derived class object, then
hibernate will first save the baseclass object then derived class object right ..!, so at the time of
saving the derived class object hibernate will copy the primary key value of the base class into the
corresponding derived class, see in the above output 10 copied into dummy1 column of CreditCard
table and 11 copied into Dummy2 column of the cheque table
Something like previous example but the changes are at mapping file only, and one more thing is..
Once we save the derived class object, then derived class data and base class data will be saved in
the derived class related table in the database
for this type we need the tables for derived classes, but not for the base class
in the mapping file we need to use one new element <union-subclass — >under <class —>