liveBook · Manning

Polymorphic query

As explained in Java Persistence with Spring Data and Hibernate epub

A polymorphic query retrieves instances of multiple entity classes matching the queried superclass or interface type.

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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains separate SELECTs, UNION construction, NULL padding, discriminator values, and association consequences.
Examples
Uses BillingDetails, CreditCard, BankAccount, repository findAll(), JPQL, and generated UNION ALL SQL.
What it assumes
Assumes Java inheritance, SQL tables, JPA repositories, and basic JPQL; explains the relational mismatch from inheritance.
What you can do after
Evaluate Hibernate inheritance mappings by comparing separate subclass SELECTs with UNION-based polymorphic loading.
How it connects
Connects inheritance mapping, polymorphic associations, Hibernate, Spring Data JPA, JPQL, and SQL UNION queries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.