首页 > 解决方案 > 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]

解决此问题的正确方法是什么?谢谢

标签: javahibernatejpaentitypersistence

解决方案


推荐阅读