Thursday, August 22, 2013

HIbernate - Inheritance – Strategy 1 : Table Per Class Hierarchy

HIbernate - Inheritance – Strategy 1 : Table Per Class Hierarchy 

Inheritance – Strategy 1 : Table Per Class Hierarchy

Inheritance Mapping

Hibernate supports 3 basic inheritance mapping strategies.
          1. Table per class hierarchy 
          2. Table per subclass 
          3. Table per concrete class 
All the classes in the hierarchy are stored in a single table (map the whole hierarchy by using a single table). Suppose you have the base Employee class, with PermanentEmployee and ContractEmployee as subclasses.

Discriminator -  The most important is the inclusion of the discriminator element.

The discriminator column is what Hibernate uses to tell the different sub-classes apart when retrieving classes from the database.

If you don't specify a discriminator value, Hibernate uses the object's class name.

The discriminator element in the example mapping tells Hibernate to look in the “EMPLOYEE_TYPE” column for a string describing the class type. (<discriminator column="EMPLOYEE_TYPE" type="string"> </discriminator>)
The discriminator is only a column in the relational table-you don't need to define it as a property in your Java object.

The subclass element contains the properties and associations belonging to the subclass. Any association element is allowed between sub- class tags. You can't have an id element or a nested subclass element. (<subclass ..> </subclass> )  The table per class hierarchy strategy requires a single table, employee (table name), to store the three types of Employee instances in below example.

Since one table contains the fields for all the objects in the hierarchy, your subclasses can‘t have columns declared as NOT NULL
 
 
 
Step 1 - Create POJO classes ( Employee.java and PermanentEmployee, ContractEmployee sub-classes )
Step 2 - Create mapping file ( employee.hbm.xml )
Step 3 - Hibernate Configurations ( hibernate.cfg.xml ) 
Step 4 - Create class to do the execution ( ExecuteEmployee.java )
 
Step 1 - Create POJO classe
 
Create POJO (Plain Old Java Object) classes that represents the Employee, PermanentEmployee and ContractEmployee.
 
 
 
 
 
Step 2 - Create mapping file
 
Create a mapping file “employee.hbm.xml” which maps “Employee.java” POJO and the “employee” table in the database.

<discriminator column="EMPLOYEE_TYPE" type="string"> </discriminator> <subclass name="pojo.PermanentEmployee" discriminator-value="emp_permanet"> ... </subclass> <subclass name="pojo.ContractEmployee" discriminator-value="emp_contract"> ... 
</subclass>
 
 
Step 3 - Hibernate Configurations
 
Create configuration file name as hibernate.cfg.xml and save it.
 
 
 
Step 4 - Create Execute class

Create a ExecuteEmployee class to do the execution.
 
 
 

Out put on the above application as follows.