Given the following domain model, I want to load all Answer
s including their Value
s and their respective sub-children and put it in an AnswerDTO
to then convert to JSON. I have a working solution but it suffers from the N+1 problem that I want to get rid of by using an ad-hoc @EntityGraph
. All associations are configured LAZY
.
@Query("SELECT a FROM Answer a")
@EntityGraph(attributePaths = {"value"})
public List<Answer> findAll();
Using an ad-hoc @EntityGraph
on the Repository
method I can ensure that the values are pre-fetched to prevent N+1 on the Answer->Value
association. While my result is fine there is another N+1 problem, because of lazy loading the selected
association of the MCValue
s.
Using this
@EntityGraph(attributePaths = {"value.selected"})
fails, because the selected
field is of course only part of some of the Value
entities:
Unable to locate Attribute with the the given name [selected] on this ManagedType [x.model.Value];
How can I tell JPA only try fetching the selected
association in case the value is a MCValue
? I need something like optionalAttributePaths
.
selected
for those answers that have aMCValue
. I disliked that this would require an additional loop and I would need to manage the mapping between the data sets. I like your idea to exploit the Hibernate cache for this. Can you elaborate on how safe (in terms of consistency) it is to rely on the cache to contain the results? Does this work when the queries are made in a transaction? I am afraid of hard to spot and sporadic lazy initialization errors. – Voltz