Consider the following JPA entity structure:
Code:
@Entity
@Inheritance(strategy = TABLE_PER_CLASS)
public abstract class Case {
@ManyToOne(fetch = LAZY)
private Partner p;
}
@Entity
public class SpecialCase extends Case {
}
@Entity
@Inheritance(strategy = SINGLE_TABLE)
public abstract class Partner {
}
@Entity
public class Person extends Partner {
@ElementCollection(fetch = LAZY)
private final List<A> as = new ArrayList<>();
@OneToMany(fetch = LAZY)
private final List<B> bs = new ArrayList<>();
}
@Entity
public class Company extends Partner {
@Embedded
private C c;
@OneToOne(fetch = LAZY)
private D d;
}
I want to create a query that returns a subset of SpecialCases such that the Partner field `p` from its super class Case is fetched in a polymorph way (Persons and Companies) while eagerly. In addition, for a Person, I want to fetch the `as` and `bs` eagerly, while for a Company, I want to fetch `d` eagerly (`c` doesn't matter here). Note that I don't want to achieve that by using fetch type EAGER. Instead, I have created to following named EntityGraph that is placed on the SpecialCase entity:
Code:
@NamedEntityGraph(
name = "SpecialCaseEG",
attributeNodes = {
@NamedAttributeNode(value = "p", subgraph = "PartnerEG")
},
subgraphs = {
@NamedSubgraph(name = "PartnerEG", attributeNodes = {})
},
subclassSubgraphs = {
@NamedSubgraph(name = "PartnerEG", type = Person.class, attributeNodes = { @NamedAttributeNode("as"), @NamedAttributeNode("bs") }),
@NamedSubgraph(name = "PartnerEG", type = Company.class, attributeNodes = { @NamedAttributeNode("c") })
}
)
My first question is whether the entity graph is specified correctly? In particular, I could not find any references on how to use `subclassSubgraphs` on the net except
http://stackoverflow.com/questions/29603695/jpa-2-1-namedsubgraph-in-hibernate-ignoring-subclasses.
Anyway, using Hibernate 5.0.7, Wildly 10, and `org.hibernate.dialect.PostgreSQL94Dialect`, it does not work as intended: in a Database that contains SpecialCases with Persons only, the `as`and `bs` are lazy lists that are not eagerly loaded. The only way I was able to achieve eager loading of them was to set their fetch type to EAGER with the downside that this creates the infamous n+1 select problem.
I'm not sure whether the entity graph is wrong, whether what I want to achieve is not possible at all using an entity graph, or whether there is there a bug in Hibernate?
Thanks.