Persistence Strategies

From sheep
Jump to navigation Jump to search

Inheritance and persistence

Single Table

Default mechanism in EJB3

  • Objects discriminated by extra column in table
    • specify mechanism: @Inheritance(Strategy=InheritanceType.SINGLE_TABLE)
    • must specify the column name: @DiscriminatorColumn(name="...
    • Each entity must specify values: @DiscriminatorValue(value="... - default = name of subclass

Implications

  • column for each field in every subclass
    • can result in a lot of redundant columns
  • unable to exploit constraints - null values may be required for some subclasses and not others
    • can overcome with triggers

Joined Table

    • specify mechanism: @Inheritance(Strategy=InheritanceType.JOINED)
  • separate table for each entity in hierarchy
  • core table with primary key and columns for common elements
  • sub tables use same primary key as core table and include columns for additional attributes
  • discriminator column used to easily identify subtype see #Single Table
  • Also specify table join column @PrimaryKeyJoinColumn(name="...

Implications

  • cleaner design - easy to enforce constraints
  • worse performance than Single Table as requires joining tables

Table per Class

Optional for providers to implement

    • specify mechanism: @Inheritance(Strategy=InheritanceType.TABLE_PER_CLASS)
  • All classes have unique tables
    • No relationship exists between tables
  • primary keys across all tables must be unique
  • All inherited columns duplicated in each sub table

Implications

  • Poor OO design
  • Poor performance
  • data can be pulled from one table in single query
  • poor support for polymorphic queries - queries must union all tables

Inheritance from non Entity classes

Annotate with: @MappedSuperClass

  • no associated table

Polymorphic associations

Polymorphic associations work in JPA

  • When base class has an association to another object
  • Sub classes inherit this association