首页 > 解决方案 > Spring休眠实体图不填充对象

问题描述

我有以下类,当我的spring数据调用find commentById时,我可以看到选择在带有外部连接的日志中完成......但是当我在intelliJK中检查对象时没有数据......相反,当另一个选择发生时我做comment.getUser()..为什么我的实体grahh没有加载数据。

@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;
    
    //...
}

标签: hibernatespring-data-jpa

解决方案


您必须在执行查询时实际指定要使用的实体图。使用 Spring Data JPA,您可以通过@EntityGraph在查询方法上添加注释来做到这一点。

public interface CommentRepository extends JpaRepository<Comment, Long> {

    @EntityGraph(value = "comment-entity-graph")
    Comment findById(Long id);
}

有关更详细的示例,请参见https://www.baeldung.com/spring-data-jpa-named-entity-graphs


推荐阅读