'JPA fetch collection of subclass

I have a case where we have an inheritance strategy like this (this is an example of the jpa wiki, our real example is an other business case :))

@Entity
@Inheritance
@DiscriminatorColumn(name="PROJ_TYPE")
@Table(name="PROJECT")
public abstract class Project {
  @Id
  private long id;
  ...
}
@Entity
@DiscriminatorValue("L")
public class LargeProject extends Project {
  @OneToMany
  private Set<Member> members;
}
@Entity
@DiscriminatorValue("S")
public class SmallProject extends Project {
}

I have a bunch of projects in my database and want to fetch all the projects at once, but by doing this, i also want to fetch my list of members at once. Is there a way to do this with jpql? I know the TYPE annotation allows me to look at the type, but can I combine this with a JOIN FETCH?

I'm using hibernate, but don't want to downgrade back to the hibernate api if I don't need to



Solution 1:[1]

JPA and Hibernate doesn't support fetching associations from subclasses, unless the property is also present in the topmost member of the hierarchy. But according to this post (https://thorben-janssen.com/fetch-association-of-subclass/) you can work around this limitation by exploiting hibernate's level 1 cache mechanism.

In you case you'll fetch all instances of Member first, in a separated query, and then perform your query on Project, letting LargeProject.members to be Lazy loaded. Instead of performing N + 1 SELECTs, hibernate will fetch those from the cache.

Solution 2:[2]

A bit late but I found a way by using only JPQL. In your case :

SELECT p FROM Project p JOIN FETCH ((TREAT(p as LargeProject)).members)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Victor Högemann
Solution 2