I am working with Spring Data JPA and Entity Graphs.
I have the following Entity structure:
Result
entity has a list of SingleQuestionResponse
entities, and the SingleQuestionResponse
entity has a set of Answer
entities (markedAnswers).
public class Result {
...
@OneToMany(cascade = CascadeType.PERSIST)
@JoinColumn(name = "result_id", nullable = false)
private List<SingleQuestionResponse> responses;
...
}
public class SingleQuestionResponse {
...
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "singlequestionresponses_answers",
joinColumns = @JoinColumn(name = "single_question_response_id"),
inverseJoinColumns = @JoinColumn(name = "answer_id")
)
private Set<Answer> markedAnswers;
...
}
and Answer
just has simple-type fields.
Now, I would like to be able to fetch Result, along with all responses, and the markedAnswers in one query. For that I annotated the Result
class with:
@NamedEntityGraph(name = "graph.Result.responsesWithQuestionsAndAnswersEager",
attributeNodes = @NamedAttributeNode(value = "responses", subgraph = "responsesWithMarkedAnswersAndQuestion"),
subgraphs = {
@NamedSubgraph(name = "responsesWithMarkedAnswersAndQuestion", attributeNodes = {
@NamedAttributeNode("markedAnswers"),
@NamedAttributeNode("question")
})
}
)
an example of usage is:
@EntityGraph("graph.Result.responsesWithQuestionsAndAnswersEager")
List<Result> findResultsByResultSetId(Long resultSetId);
I noticed, that calling the findResultsByResultSetId
method (and other methods using this entity graph) results in responses
(SingleQuestionResponse
entities) being multiplied by the number of markedAnswers
. What I mean by that is that result.getResponses()
returns more SingleQuestionResponse
objects than it should (it returns one response object per each markedAnswer).
I realize this is due to Hibernate making a Cartesian product with the join, but I have no idea how to fix it.
Can you help please? Thanks