Issue
I have the the following classes, i can see the select being done in logs with outer joins when my spring data calls the find commentById... but when i inspect the object in intelliJK there is no data.. instead another select takes place when i do comment.getUser().. why is my entity grahh not loading data.
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
//...
}
@Entity
public class Post {
@OneToMany(mappedBy = "post")
private List<Comment> comments = new ArrayList<>();
//...
}
@NamedEntityGraph(
name = "comment-entity-graph",
attributeNodes = {
@NamedAttributeNode("user"),
@NamedAttributeNode("post", subgraph = "post.comments"),
},
subgraph= { @NamedSubgraph=(name= "post.comments", attributeNodes= { @NamedAttributeNode("comments")})
}
)
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String reply;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private Post post;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private User user;
//...
}
Solution
You have to actually specify the entity graph to be used when performing the query. With Spring Data JPA you do that by adding an @EntityGraph
annotation on your query method.
public interface CommentRepository extends JpaRepository<Comment, Long> {
@EntityGraph(value = "comment-entity-graph")
Comment findById(Long id);
}
For a more verbose example see https://www.baeldung.com/spring-data-jpa-named-entity-graphs
Answered By - Jens Schauder