Suppose a Table per subclass inheritance relationship which can be described bellow (From wikibooks.org - see here)
Notice Parent class is not abstract
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Project {
@Id
private long id;
// Other properties
}
@Entity
@Table(name="LARGEPROJECT")
public class LargeProject extends Project {
private BigDecimal budget;
}
@Entity
@Table(name="SMALLPROJECT")
public class SmallProject extends Project {
}
I have a scenario where i just need to retrieve the Parent class. Because of performance issues, What should i do to run a HQL query in order to retrieve the Parent class and just the Parent class without loading any subclass ???
Actually, there is a way to get just the superclass, you just need to use the native query from JPA, in my case I'm using JPA Repositories it would be something like that:
The flag nativeQuery as true allow running the native SQL on database.
If you are using Entity Manager check this out: https://www.thoughts-on-java.org/jpa-native-queries/
A workaround is described below:
Define your
Parent
class as MappedSuperClass. Let's suppose the parent class is mapped ToPARENT_TABLE
For each subclass, extend the
AbstractParent
class and define its SecondaryTable. Any persistent field defined in the parent class will be mapped to the table defined by SecondaryTable. And finally, use AttributeOverrides if neededAnd define another Entity with the purpose of retrieving just the parent class
Nothing else. See as shown above i have used just JPA specific annotations
Update: It appears the first option doesn't work as I thought.
First option:
Specify the class in the where clause:
Second option:
Use explicit polymorphism that you can set using Hibernate's
@Entity
annotation:This is what Hibernate Core documentation writes about explicit polymorphism:
See also