gpt4 book ai didi

java - hibernate 映射 : OneToMany and OneToOne on child object property

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:03:39 24 4
gpt4 key购买 nike

这是父类 Enterprise。它有雇主,其中一位是企业总裁。

@Entity
class Enterprise
{
// fields

@OneToMany
public List<Employee> getEmployers()
// implementation

@OneToOne
public Employee getPresident()
// implementation

}

这是子 Employee 类。它只有关于他工作的 Enterprise 的信息。但问题是我应该使用什么关联?

@Entity
class Employee
{
// fields

// what association should I use?
public Enterprise getEnterprise()
// implementation
}

最佳答案

鉴于您已经定义了 Enterprise->Employers@OneToMany 的关联,这意味着 Employer 只属于一个 Enterprise,你应该使用 @ManyToOne,这意味着每个 Employer 都属于 max。 1 Enterprise,但是 Enterprise 可以引用许多 Employers

您可以使用注释中的 mapped-by 属性仅在一侧定义关联细节(连接列等):

@Entity
class Enterprise
{
@OneToMany(mapped-by="enterprise")
public List<Employee> getEmployers()
// implementation

@OneToOne
public Employee getPresident()
// implementation
}

@Entity
class Employee
{
@ManyToOne
@JoinTable ( name="Enterprise", joinColumns={ @JoinColumn(name="ENT_ID", referencedColumnName="ENT_ID") }
public Enterprise getEnterprise()
// implementation
}

如果 Employer 可能是他受雇的另一家 Enterprise 的总裁(似乎不太可能,除非一个人可以成为一家企业的总裁而不被其雇用),并且如果您需要从 Employer 实体访问 Enterprise,而 Employer 是总裁,则需要添加另一个关联,理想情况下使用 @OneToOne(您会遇到问题,因为 @OneToOne 关系要求两个实体具有相同的 @Id 类)。在这种情况下,出于实际原因,我将使用 @ManyToOne 注释 Employer 上的 getPresidedEnterprise() 方法。

关于java - hibernate 映射 : OneToMany and OneToOne on child object property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7647584/

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