Hibernate映射:OneToMany和OneToOne在子对象属性上的使用 [英] Hibernate mapping: OneToMany and OneToOne on child object property
问题描述
这是父类Enterprise。它有雇主,其中一个是企业总裁。
@Entity
类企业
{
//字段
@OneToMany
公共列表< Employee> getEmployers()
//执行
@OneToOne
public Employee getPresident()
//执行
这是child Employee类。它只有关于他工作的企业的信息。但问题是我应该使用哪种关联?
@Entity
类员工
{
//字段
//我应该使用哪种关联?
public Enterprise getEnterprise()
//执行
}
鉴于您定义了企业
- > 雇主
与 @OneToMany
,这意味着雇主
只属于一个企业
>,你应该使用 @ManyToOne
,这意味着每一个雇主
都属于最大值。 1 企业
,但是企业
可以引用许多雇主
。
您可以使用 mapped-by $ c $来定义关联细节(连接列等) c $>
@Entity
class企业
{
@OneToMany (映射=企业)
公共列表<员工> getEmployers()
//执行
@OneToOne
public Employee getPresident()
//执行
}
@ Entity
class Employee
{
@ManyToOne
@JoinTable(name =Enterprise,joinColumns = {@JoinColumn(name =ENT_ID,referencedColumnName =ENT_ID)}
public Enterprise getEnterprise()
//执行
}
如果 Here is parent class Enterprise. It has employers and one of them is president of enterprise. Here is child Employee class. It has only info about Enterprise where he works. But question is what association should I use?
Given that you've defined the You can define the association specifics (join columns, etc) in one of the sides only, using the In case an 这篇关于Hibernate映射:OneToMany和OneToOne在子对象属性上的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!雇主
可以担任其职位的其他雇主
的 Enterprise
是来自雇主
实体的总裁,您需要添加另一个关联,理想情况下使用 @OneToOne
(您会遇到问题,因为@OneToOne关系需要两个实体具有相同的@Id类)。在这种情况下,我会anno使用 @ManyToOne
对雇主
上的 getPresidedEnterprise()
出于实际的原因。 @Entity
class Enterprise
{
// fields
@OneToMany
public List<Employee> getEmployers()
// implementation
@OneToOne
public Employee getPresident()
// implementation
}
@Entity
class Employee
{
// fields
// what association should I use?
public Enterprise getEnterprise()
// implementation
}
Enterprise
->Employers
association with @OneToMany
, which means that an Employer
belongs to only one Enterprise
, you should be using @ManyToOne
, meaning that every Employer
belongs to max. 1 Enterprise
, but an Enterprise
can reference many Employers
.mapped-by
attribute in the annotation:@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
could be president of a different Enterprise
in which he is employed (seems unlikely, unless one can be president of an enterprise without being employed by it), and in case you needed to access the Enterprise
of which the Employer
is president from the Employer
entity, you would need to add another association, ideally with @OneToOne
(you would encounter problems, because @OneToOne relations require both entities to have the same @Id class). In this case I would annotate the getPresidedEnterprise()
method on Employer
with @ManyToOne
for practical reasons.