我的员工表有coloumns:
employee_id
department_id
firstname
lastname
address
..
和employee_identity表:
employee_identity_id
employee_id
ssn
mother_name
father_name
...
我有以下表格的实体:
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
...
// bi-directional one-to-one association to EmployeeIdentity
@PrimaryKeyJoinColumn(name = "employee_id", referencedColumnName = "employee_id")
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private EmployeeIdentity employeeIdentity;
public Employee() {
employeeIdentity = new EmployeeIdentity();
}
...
}
@Entity
@Table(name = "employee_identity")
@NamedQuery(name = "EmployeeIdentity.findAll", query = "SELECT e FROM EmployeeIdentity e")
public class EmployeeIdentity implements Serializable {
...
// bi-directional one-to-one association to Employee
@OneToOne(fetch = FetchType.EAGER)
@PrimaryKeyJoinColumn(name = "employee_id", referencedColumnName = "employee_id")
private Employee employee;
...
}
我想创建一个员工对象并设置其employeeIdentity的字段并最终保留它们。当我提交员工时,我可以将我的数据写入employee_identity,但employee_id coloumn为null。这是可能的,还是我应该单独提交员工对象和employeeIdentity对象?
答案 0 :(得分:0)
您的映射是错误的。双向关联的一端必须是反面,因此具有mappedBy
属性,并且没有PrimaryKeyJoinColumn
关联。
PrimaryKeyJoinColumn
也不是正确的注释,因为它意味着:此实体的主键也是另一个实体的连接列。你应该在EmployeeIdentity.employee上有@JoinColumn
,这应该是所有者。
如果您希望JPA了解关联,您必须注意初始化所有者方(没有mappedBy
属性的一方,所以EmployeeIdentity.employee
)。