| 20 | The OO notion of inheritance may be expressed in Hibernate using 4 different strategies, see Java Persistence with Hibernate by Christian Bauer and Gavin King. They are |
| 21 | |
| 22 | * Table per concrete class with implicit polymorphism |
| 23 | * Table per concrete class with unions |
| 24 | * Table per class hierarchy |
| 25 | * Table per subclass |
| 26 | |
| 27 | The first strategy creates a different table for each subclass, and those tables all contain (repeat) the data from the common base class. The Hibernate mapping is unaware of the inheritance relation. The base class definition is thus denormalized. It is impossible to define polymorphic associations and problematic to define polymorphic queries. |
| 28 | |
| 29 | The second strategy also employs different tables for each subclass (thus base class columns are denormalized), but now the Hibernate mapping is made aware of the inheritance relation. This allows for polymorphic associations and avoids repeating the base class mapping multiple times in the Hibernate mapping. |
| 30 | |
| 31 | The third strategy uses a single table for the base class and all subclasses. The table's columns are a union of all columns of the base and subclasses. This will require that all subclass properties are nullable. In case of larger inheritance structures, this strategy would lead to everything being chucked together in one table. |
| 32 | |
| 33 | The fourth strategy is to represent inheritance relationships as relational foreign key associations. Every class/subclass that declares persistent properties—including abstract classes and even interfaces—has its own table. The primary advantage of this strategy is that the SQL schema is normalized. A polymorphic association to a particular subclass may be represented as a foreign key referencing the table of that particular subclass. This seems a preferred strategy but its performance may be detrimental for large class hierarchies as queries require a join across many tables. |