gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:06:13 24 4
gpt4 key购买 nike

我知道我的标题不清楚,但我不知道如何用几句话来解释我的问题。

我有两个具有双向映射的类。 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 的字段。

我记得有一种方法可以让您在单个表中保存一个 Entity,它可以被许多不同的 Entities 映射。我记得我需要在表中添加一个字段来区分 Image.class 是“绑定(bind)”到 Father.class 还是 Mother.class.

我再也无法在 Internet 上找到该文档。

最佳答案

请注意,“字段”不是描述关系的正确术语。 FatherMotherImage关系,这可能是单向的,即 Image code> 不知道它属于哪个实体。

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


如果您真的需要知道这一点并且需要 Hibernate 能够导航关系,那么您必须使用一个通用的父类(super class)(也需要是一个实体,即使没有实例)和可能的类继承。

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

关于java - 由其他许多不同实体映射的实体(使用 Hibernate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com