A polymorphic association targets a superclass while referring at runtime to an instance of any concrete subtype. For example, User.defaultBilling can reference either CreditCard or BankAccount. SQL foreign keys normally identify exactly one target table, so relational schemas need an ORM inheritance strategy to represent this relationship. section 1.2.2 section 7.8
A polymorphic many-to-one association works as follows:
- Map the target superclass as an entity with inheritance, and declare the association against that superclass. section 7.8.1
- Store the relationship in the owning table; User receives a nullable DEFAULTBILLING_ID join column because no default billing method may be assigned. section 7.8.1
- Assign a concrete subtype such as CreditCard, persist both entities, and navigate the association later; Hibernate retrieves the concrete instance and dispatches its pay method. section 7.8.1
- Apply the same idea to one-to-one associations; plural associations require mapping the corresponding collection relationship. section 7.8.1
Default billing details
A User declares `@ManyToOne private BillingDetails defaultBilling;`. A CreditCard is assigned to that property and saved with the User. Loading users later allows `users.get(0).getDefaultBilling().pay(123)` to invoke the concrete billing subtype.
Inheritance strategy affects how well polymorphic associations are supported. Table-per-concrete-class with implicit polymorphism is simple but weak for these associations; table-per-concrete-class with unions supports them conditionally. Table-per-class-hierarchy favors performance and simplicity, while joined subclass tables favor normalization and integrity at possible query cost. section 7.9
Use the class diagram to see User.defaultBilling pointing to either CreditCard or BankAccount. section 7.8
