同一实体上的JPA OneToOne和OneToMany

同一实体上的JPA OneToOne和OneToMany

问题描述:

可能重复:
两个实体之间的JPA OneToOne和ManyToMany

我一直在寻找无济于事的解决方案.我的问题是我有两个实体雇员"和部门"许多员工属于一个部门一个部门由一名雇员领导.随时都会出现错误,同时介绍@OneToOne和@OneToMany.这是代码

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. 在创建或要求JPA创建 Employee 的实例时, Employee 会尝试实例化 Department ,将 Employee ...实例化为无穷大.

  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.

从类定义中删除 = new Employee()和= new Department()表达式;使用适当的setter方法.

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

验证是否在 Department 表上定义了定义一对一关系的SQL列;特别是 Department 表具有一个引用 Employee 的外键.这样做的基础是,应在没有没有SQL外键的JPA实体上定义 @OneToOne(mappedBy ="...")引用执行 的实体.

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();

以及部门上的相应字段:

@OneToOne
public Employee deptHead = new Employee();

depthead 和 deptHead 之间的情况不匹配.

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