Tuesday, March 2, 2010

JPA Inheritance mapping strategies

The mapping of class hierarchies is specified through metadata.
There are three basic strategies that are used when mapping a class or class hierarchy to a relational
database:
  • a single table per class hierarchy
  • a table per concrete entity class
  • a strategy in which fields that are specific to a subclass are mapped to a separate table than the
  •  fields that are common to the parent class, and a join is performed to instantiate the subclass.
              An implementation is required to support the single table per class hierarchy inheritance mapping strat-egy and the joined subclass strategy. Support for the table per concrete class inheritance mapping strategy is optional in this release.
              Support for the combination of inheritance strategies within a single entity inheritance hierarchy is not required by this specification.

2.1.10.1 Single Table per Class Hierarchy Strategy
         In this strategy, all the classes in a hierarchy are mapped to a single table. The table has a column that serves as a “discriminator column”, that is, a column whose value identifies the specific subclass to which the instance that is represented by the row belongs.
         This mapping strategy provides good support for polymorphic relationships between entities and for queries that range over the class hierarchy. It has the drawback, however, that it requires that the columns that correspond to state specific to the subclasses be nullable.

2.1.10.2 Table per Concrete Class Strategy
         In this mapping strategy, each class is mapped to a separate table. All properties of the class, including inherited properties, are mapped to columns of the table for the class.
         This strategy has the following drawbacks:
               • It provides poor support for polymorphic relationships.
               • It typically requires that SQL UNION queries (or a separate SQL query per subclass) be issued for queries that are intended to range over the class hierarchy.

2.1.10.3 Joined Subclass Strategy

         In the joined subclass strategy, the root of the class hierarchy is represented by a single table. Each subclass is represented by a separate table that contains those fields that are specific to the subclass (not inherited from its superclass), as well as the column(s) that represent its primary key. The primary key  column(s) of the subclass table serves as a foreign key to the primary key of the superclass table. This strategy provides support for polymorphic relationships between entities.
         It has the drawback that it requires that one or more join operations be performed to instantiate instances of a subclass. In deep class hierarchies, this may lead to unacceptable performance. Queries that range over the class hierarchy likewise require joins.


SOURCE: EJB 3.0 JPA Specification


No comments: