Javatpoint Logo
Javatpoint Logo

Table Per Subclass Example using xml file

In case of Table Per Subclass, subclass mapped tables are related to parent class mapped table by primary key and foreign key relationship.

The <joined-subclass> element of class is used to map the child class with parent using the primary key and foreign key relation.

In this example, we are going to use hb2ddl.auto property to generate the table automatically. So we don't need to be worried about creating tables in the database.

Let's see the hierarchy of classes that we are going to map.

table per concrete class

Let's see how can we map this hierarchy by joined-subclass element:

In case of table per subclass class, there will be three tables in the database, each representing a particular class.

The joined-subclass subelement of class, specifies the subclass.

The key sub-element of joined-subclass is used to generate the foreign key in the subclass mapped table. This foreign key will be associated with the primary key of parent class mapped table.


The table structure for each table will be as follows:

Table structure for Employee class

table per subclass class

Table structure for Regular_Employee class

table per subclass class

Table structure for Contract_Employee class

table per subclass class

Example of Table per subclass class

In this example we are creating the three classes and provide mapping of these classes in the employee.hbm.xml file.

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create the three classes for the above hierarchy:

File: Employee.java
File: Regular_Employee.java
File: Contract_Employee.java

2) Create the mapping file for Persistent class

The mapping has been discussed above for the hierarchy.

File: employee.hbm.xml

3) create configuration file

Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:

Now the configuration file will look like this:

File: hibernate.cfg.xml

The hbm2ddl.auto property is defined for creating automatic table in the database.


4) Create the class that stores the persistent object

In this class, we are simply storing the employee objects in the database.

File: StoreData.java






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA