A polymorphic query retrieves instances of multiple entity classes through a queried superclass or interface. In an inheritance model, querying BillingDetails can return CreditCard and BankAccount objects, even though SQL tables do not inherently represent the hierarchy. section 1.2.2 section 7.1
Inheritance mappings determine how the query reaches concrete tables:
- Implicit polymorphism queries each concrete subclass table separately, then combines the results in Hibernate; queries against one concrete class use a single statement. section 7.1
- TABLE_PER_CLASS uses a UNION query with aligned columns, NULL padding, and a discriminator literal so Hibernate can instantiate the correct subclass. section 7.2
- The UNION strategy can also support associations targeting the superclass, because Hibernate can simulate one association target across the concrete tables. section 7.2
Querying BillingDetails
A repository call such as billingDetailsRepository.findAll(), or the JPQL query select bd from BillingDetails bd, retrieves both billing-detail subclasses. With TABLE_PER_CLASS, Hibernate generates a UNION ALL over CREDITCARD and BANKACCOUNT, pads missing subclass columns with NULL, and adds a class marker. section 7.2
