Expensive multi-table JOIN query when association is initialized in Hibernate
Issue
- Associating several distinct subclasses in a
JOINEDinheritance hierarchy with another entity (e.g.Owner) - The
targetEntityin each@OneToManyassociation was added to resolve the join column defined in the superclass. - Restrictions were applied to resolve discrepancies between the classes since re-using the foreign key
-
Each of the associations are unidirectional
@MappedSuperclass public class Task ... { ... @Column(name = "OWNERID") public long getOwnerId() { ... } ... } @Entity @Inheritance(strategy = InheritanceType.JOINED) public class ProjectTask extends Task ... { ... } @Entity @Inheritance(strategy = InheritanceType.JOINED) public class LearningTask extends Task ... { ... } @Entity @Inheritance(strategy = InheritanceType.JOINED) public class ReviewTask extends Task ... { ... } @Entity public class Owner { ... @OneToMany(targetEntity = Task.class, ...) @JoinColumn(name = "OWNERID") @Where(...) @Filter(...) public Set<ProjectTask> getProjectTasks() { ... } @OneToMany(targetEntity = Task.class, ...) @JoinColumn(name = "OWNERID") @Where(...) @Filter(...) public Set<LearningTask> getLearningTasks() { ... } @OneToMany(targetEntity = Task.class, ...) @JoinColumn(name = "OWNERID") @Where(...) @Filter(...) public Set<ReviewTask> getReviewTasks() { ... } } -
At runtime, when any one of the associations is navigated/traversed (explicitly or implicitly) a join query including each of the sibling classes is observed in the log
... DEBUG [org.hibernate.SQL] ... select ... from Owner ... left outer join Task ... left outer join ProjectTask ... left outer join LearningTask ... left outer join ResearchTask ... ... where ...
Environment
- Red Hat JBoss Enterprise Application Platform (EAP)
- 5
- 6
- Hibernate
- 3
- 4
Subscriber exclusive content
A Red Hat subscription provides unlimited access to our knowledgebase of over 48,000 articles and solutions.
Welcome! Check out the Getting Started with Red Hat page for quick tours and guides for common tasks.
