由其他许多不同实体映射的实体(使用 Hibernate)
Entity mapped by other many different Entities (with Hibernate)
我知道我的标题不清楚,但我不知道如何用几句话来解释我的问题。
我有两个 类 具有双向映射。 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
的 "mapping"?
当然Image.class
不能有Father father
这样的字段,因为在最后一个场景中Image.class
是Mother.class
的字段而不是[=的字段14=].
我记得有一种方法可以让你在单个 table 中保存一个 Entity
,它可以被许多不同的 Entities
映射。我记得我需要在 table 中添加一个字段来区分 Image.class
是 "bound" 到 Father.class
还是 Mother.class
.
我无法再在 Internet 上找到该文档。
请注意,"field" 不是描述关系的正确术语。 Father
和 Mother
与 Image
有 关系 并且这可能是单向的,即 Image
不知道它是哪个实体属于。
这可能是最明智的方法,如果没有充分的理由要求双向关系,我建议您采用单向路线。要使关系成为单向关系,您必须使 Mother
和 Father
成为拥有方,即将图像 ID 放入它们的 tables 并从它们的 mappedby
中删除=17=] 同时从 Image
中完全删除映射。
如果您真的需要知道这一点并且需要 Hibernate 能够导航关系,那么您必须使用通用的超级 class(也需要即使没有实例也是一个实体)并且可能 table-per-class 继承。
除此之外,您可以在 Image
本身中存储有关谁与图像相关的信息,然后手动进行查找。
我知道我的标题不清楚,但我不知道如何用几句话来解释我的问题。
我有两个 类 具有双向映射。 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
的 "mapping"?
当然Image.class
不能有Father father
这样的字段,因为在最后一个场景中Image.class
是Mother.class
的字段而不是[=的字段14=].
我记得有一种方法可以让你在单个 table 中保存一个 Entity
,它可以被许多不同的 Entities
映射。我记得我需要在 table 中添加一个字段来区分 Image.class
是 "bound" 到 Father.class
还是 Mother.class
.
我无法再在 Internet 上找到该文档。
请注意,"field" 不是描述关系的正确术语。 Father
和 Mother
与 Image
有 关系 并且这可能是单向的,即 Image
不知道它是哪个实体属于。
这可能是最明智的方法,如果没有充分的理由要求双向关系,我建议您采用单向路线。要使关系成为单向关系,您必须使 Mother
和 Father
成为拥有方,即将图像 ID 放入它们的 tables 并从它们的 mappedby
中删除=17=] 同时从 Image
中完全删除映射。
如果您真的需要知道这一点并且需要 Hibernate 能够导航关系,那么您必须使用通用的超级 class(也需要即使没有实例也是一个实体)并且可能 table-per-class 继承。
除此之外,您可以在 Image
本身中存储有关谁与图像相关的信息,然后手动进行查找。