问题
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.
When you create, or ask JPA to create, an instance of
Employee
, theEmployee
attempts to instantiate aDepartment
, which instantiates anEmployee
..., to infinity.Remove the
= new Employee()
and =new Department()
expressions from the class definition; use appropriate setter methods.Verify that the SQL column defining the one-to-one relationship is defined on the
Department
table; specifically theDepartment
table has a foreign-key referencing anEmployee
. 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