java - JPA Entity 依赖于独立的实体
问题描述
我有两个实体,帖子和图片。我想保持图片尽可能独立。帖子应该有图片,但这不是强制性的。现在实体看起来像这样。
@Entity
@Table(name = "pictures")
public class Picture implements Comparable<Picture> {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String file;
//getters and setters
}
@Entity
@Table(name = "posts")
public class Post implements Comparable<Post> {
@Id
@GeneratedValue
private long id;
//some extra fields
private Picture picture;
//getters and setters
}
问题是我不知道我应该对图片字段进行注释以建立连接。我尝试使用 @OneToOne 和 @MapsId 注释它(基于 Vlad Mihalcea 的指南),但是当我尝试使用空图片字段保存 Post 实体时,我收到这样的错误
org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.acme.Post.picture]
解决此问题的正确方法是什么?谢谢
解决方案
推荐阅读
- python - 正则表达式魔法,有了它,VS Code 毁了我的整个 Jupyter Notebook
- python - 如何连接表并计算sqlalchemy中指定列的数量?
- angular - 如何从数组中获取对象?
- r - 从 SpatialPolygonsDataFrame 创建镶嵌?
- html - HTML - 另一个图像上的图像触发弹出窗口
- java - 如何在 Spring REST 控制器中获取原始 JSON 正文?
- typescript - 打字稿:试图扩展字符串类...无法在我的方法中获取对字符串值的引用
- javascript - useEffect 重新渲染上下文 api 消费者组件
- python - 删除以特定字符串开头的每个单词
- winforms - 在 Windows 桌面应用程序中实现帮助功能的最佳方法 - 限制应用知识库以授权访问