Home » Hibernate Table per subclass using Annotation tutorial example

Hibernate Table per subclass using Annotation tutorial example

by Online Tutorials Library

Table Per Subclass using Annotation

As we have specified earlier, in case of table per subclass strategy, tables are created as per persistent classes but they are treated using primary and foreign key. So there will not be any duplicate column in the relation.

We need to specify @Inheritance(strategy=InheritanceType.JOINED) in the parent class and @PrimaryKeyJoinColumn annotation in the subclasses.

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

table per subclass strategy

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 using Annotation

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) Add project information and configuration in pom.xml file.

Open pom.xml file and click source. Now, add the below dependencies between <dependencies>….</dependencies> tag.


3)Create the 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.


3) Create the class that stores the persistent object

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

File: StoreData.java



Next TopicCollection Mapping

You may also like