Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

java - Hibernate mapping: OneToMany and OneToOne on child object property

Here is parent class Enterprise. It has employers and one of them is president of enterprise.

@Entity
class Enterprise
{
   // fields

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

   @OneToOne
   public Employee getPresident()
   // implementation

}

Here is child Employee class. It has only info about Enterprise where he works. But question is what association should I use?

@Entity
class Employee 
{
   // fields

   // what association should I use?
   public Enterprise getEnterprise()
   // implementation
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Given that you've defined the 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.

You can define the association specifics (join columns, etc) in one of the sides only, using the 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
}

In case an 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...