Hibernate mapping: OneToMany and OneToOne on child object property

天大地大妈咪最大 提交于 2019-11-29 10:50:33

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.

Use @ManyToOne annotation. It is the opposite side of a one-to-many relation. It says an employee can have one enterprise, but an enterprise can have many employees.

You should have two properties on the Employee class. Employee table should have a reference to an enterprise, ad enterprise should have a reference to an employee-president.

(you could also probably subclass an Employee based on the isPresident flag column, but I don't have experience with that)

@Entity    
class Enterprise    
{    
    // fields

    @OneToMany(mappedBy="enterprise")    
    public List<Employee> getEmployees(){} 

    @OneToOne
    @JoinColumn(name="PRESIDENT_ID")
    public Employee getPresident(){}
}    

@Entity 
class Employee  
{ 
    // fields

    @ManyToOne
    @JoinColumn(name="ENTERPRISE_ID")
    public Enterprise getEnterprise(){}

    @OneToOne(mappedBy="President")
    public Enterprise getMyEnterprise(){}
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!