Polymorphic queries in Hibernate mean you can query a superclass entity and automatically retrieve instances of all its subclasses — without explicitly mentioning each subclass.
This happens because Hibernate maps your Java inheritance hierarchy, and HQL supports it natively.
🔹 When does it matter?
- When you have an inheritance strategy in your entity model (e.g., single-table, joined, or table-per-class), and you want to fetch all entities of a base type, including any subclasses.
🔹 Example inheritance:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Animal {
@Id
private Long id;
private String name;
}
@Entity
public class Dog extends Animal {
private String breed;
}
@Entity
public class Cat extends Animal {
private String color;
}
🔹 Polymorphic query example:
Fetch all animals, regardless of subclass:
Session session = sessionFactory.openSession();
String hql = "FROM Animal"; // polymorphic: returns Dogs + Cats
List<Animal> animals = session.createQuery(hql, Animal.class).list();
for (Animal animal : animals) {
System.out.println(animal.getName());
if (animal instanceof Dog) {
System.out.println("Dog breed: " + ((Dog) animal).getBreed());
} else if (animal instanceof Cat) {
System.out.println("Cat color: " + ((Cat) animal).getColor());
}
}
session.close();
✅ Here, Hibernate executes a single HQL query on the Animal
base type → but it returns a mixed list of Dog
and Cat
entities.
🔹 Why is this powerful?
✅ You don’t need separate queries for each subclass.
✅ Maintains object-oriented behavior → lets you work naturally with inheritance in your domain model.
✅ Database schema complexities (e.g., joined tables) are abstracted away by Hibernate.
🔹 Key point:
Polymorphic queries work automatically with all Hibernate inheritance strategies:
- Single table
- Joined tables
- Table-per-class
With HQL, polymorphic queries let you query a superclass and retrieve instances of all mapped subclasses, seamlessly integrating your object-oriented design with your relational database.