JPA OneToOne and OneToMany on the same entity [duplicate]

筅森魡賤 提交于 2021-02-19 05:48:09

问题


Possible Duplicate:
JPA OneToOne and ManyToMany between two entities

I've searched for a solution to no avail. My question is I have two entities "Employee" and "Department" Many Employees belongs to One Department And One Department is headed by One Employee. Am getting errors anytime introduce both the @OneToOne and @OneToMany. This is the code

public class Department {
@Required
public String deptName; 

@OneToMany(mappedBy="dept")
public List<Employee> employees = new ArrayList<Employee>();

@OneToOne
public Employee deptHead = new Employee();

    .....   

}

public class Employee{
@Required
public String surname;

@Required
public String othernames;   

@OneToOne(mappedBy="depthead")
public Department headedBy = new Department();

@ManyToOne
public Department dept = new Department();

... 
}

Is it possible to have both aNnotation and work at the same time?


回答1:


Should be.

  1. When you create, or ask JPA to create, an instance of Employee, the Employee attempts to instantiate a Department, which instantiates an Employee ..., to infinity.

    Remove the = new Employee() and = new Department() expressions from the class definition; use appropriate setter methods.

  2. Verify that the SQL column defining the one-to-one relationship is defined on the Department table; specifically the Department table has a foreign-key referencing an Employee. The basis for this is that the @OneToOne(mappedBy="...") should be defined on the JPA Entity that does not have an SQL foreign key, referencing the entity that does.


That aside, there is an issue between

@OneToOne(mappedBy="depthead")
public Department headedBy = new Department();

and the corresponding field on Department:

@OneToOne
public Employee deptHead = new Employee();

There's a mismatch in case between depthead and deptHead, respectively.



来源:https://stackoverflow.com/questions/12998788/jpa-onetoone-and-onetomany-on-the-same-entity

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