hibernate - 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;
//...
}
解决方案
您必须在执行查询时实际指定要使用的实体图。使用 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
推荐阅读
- android - “无法识别的应用程序。请确保您在继续之前信任此应用程序”在颤动条纹支付中
- mongodb - 在 Apache BSF 脚本下使用 mongo-java-drive 时出错
- git - 如何从命令行向 git commit 消息附加一行?
- java - 为什么 maven 使用 settings.xml 中未配置的目录中的本地存储库
- flutter - 是否可以通过 UDP/TCP 从 Flutter 应用程序向 .NET 应用程序发送消息?
- spring - 在 Spring Boot 应用程序中从 Zookeeper 读取类(带下划线的路径)
- python - 处理从通用句子编码器生成的大型密集向量
- html - 日期的 HTML 模式。仅第 1 个月
- asp.net - 我的 iDisposable 类中的一次性对象是否可以保证从内存中释放?
- node.js - 如何修复 NPM UNMET PEER DEPENDENCY :npm ERR! 缺少对等部门:bufferutil@^4.0.1,ws@7.2.1 需要