被其他许多不同实体映射的实体(使用Hibernate)

3

我知道我的标题不够清晰,但是我不知道如何用简洁的话语来解释我的问题。

我有两个类之间存在双向映射。其中之一是Image.class

@Entity
@Table(name = "image")
public class Image{

    @Id
    @Column(name = "id")
    @GeneratedValue
    Long id;

    @OneToOne(targetEntity = Father.class)
    @JoinColumn(referencedColumnName = "id", name="father")
    @Size(min = 1, max = 11)
    Father father;

}

以及 Father.class:

class Father{

      @Id
      @Column(name = "id")
      @GeneratedValue
      Long id;

      @OneToOne(mappedBy = "father")  
      Image pic;
}

现在,我想把 Image.class 作为其他类的字段来使用。假设我有 Mother.class
 class Mother{

          @Id
          @Column(name = "id")
          @GeneratedValue
          Long id;

          @OneToOne(mappedBy = "mother")  
          Image pic;
    }

我的问题是:我应该如何编辑Image.class的“映射”?

当然,Image.class不能像Father father一样拥有字段,因为在最后的场景中,Image.classMother.class的字段,而不是Father.class的字段。

我记得有一种方法可以在单个表中保存可以由多个不同的Entities映射的Entity。我记得我需要在表中添加一个字段来区分Image.class是与Father.class还是Mother.class“绑定”的。

我无法在互联网上找到那份文档。

1个回答

4
请注意,“field”不是描述关系的正确术语。 FatherMother将与Image存在一个关系,这可能是单向的,即Image不知道它属于哪个实体。

这可能是最明智的方法,如果没有很好的理由要求双向关系,我建议您采用单向路线。要使关系单向,您必须使MotherFather成为拥有方,即将图像ID放入其表中,并从其@OneToOne中删除mappedby,同时完全删除Image的映射。


如果您真的需要知道并且需要Hibernate能够浏览关系,那么您必须使用公共超类(即使没有实例也必须是实体)和可能的按类继承。

除此之外,您可以在Image本身中存储有关谁与图像相关的信息,并手动查找。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接