Friday, 4 October 2013

Hibernate Mapping Strategy : Table with Concrete class with implicit polymorphism.

Table with Concrete Class with Implicit Polymorphism :
As the name suggest, the polymorphic relationship is at java side while no such relationship exits on database layer.

Example :














As in the example,
We have a 3 seperate  java class - Employee, PermanentEmployee and ContractEmployee . Here Employee class is the super class of PermanentEmployee class and ContractEmployee class.

On the database side, we have just 2 tables. PermanentEmployee and ContractEmployee Table. As shown in the diagram, properties of Java Employee class is represented as columns in PermanentEmployee and ContractEmployee tables.

The mapping is also straightforward. since we have just 2 tables, we would have 2 hbm files, namely PermanentEmployee.hbm.xml and ContractEmployee.hbm.xml.

Points to Note: 
  1. Employee class in this example can be consider as an abstract class which shares some of the common properties between PermanentEmployee and ContractEmployee class. 
  2. Primary key is not shared by superclass. Each of the subclass has there own primary key.

Disadvantage of this approach:
  1. It doesn't support polymorphic relationship so well at database layer. Polymorphic relation are usually represented as foreign key relationship. If the subclass are mapped all mapped to different tables, a polymorphic association to their superclass cannot be represented as simple foreign key relationship.
  2. Since no polymorphic relationship exists for super class, a change in superclass would results in a change in all tables. Example, to add another property "department" in Employee class would results in change in PermanentEmployee and ContractEmployee Table and corresponding hbm files. 
  3. Polymorphic queries are also problematic.  Example, to query for all Employees with Email like '%some.com%', would be executed in multiple SQL SELECTS.
    • Select name, email from PermanentEmployee where  Email like '%some.com%' ;
    • Select name, email from ContractEmployeewhere  Email like '%some.com%' ;


When to Use :

  1. When implicit polymorphism is necessary when mapping legacy models where the tables do not share many common properties.
  2. This approach can also be used when modification to the superclass is highly unlikely in future.



No comments:

Post a Comment