使用以下代码
@Embeddable
public class EmployeeId implements Serializable {
@Column(name = "company_id")
private Long companyId;
@Column(name = "employee_id")
private Long employeeNumber;
}
@Entity
public class Employee {
@EmbeddedId
private EmployeeId id;
private String name;
@MapsId("name=companyId")
@ManyToOne
@JoinColumn(name = "company_id")
private Company company;
}
尝试保留或合并Employee
实体时,我们可以看到尝试将NULL
插入到company_id字段中。
如何避免插入NULL
?
答案 0 :(得分:1)
即使使用布线,在创建新对象(未从持久性上下文中提取)时,company
字段仍将为null
。
创建新的Employee
实体时,您需要确保初始化company
属性:
@Entity
public class Employee {
@EmbeddedId
private EmployeeId id;
private String name;
@MapsId("name=companyId")
@ManyToOne
@JoinColumn(name = "company_id")
private Company company;
public Employee() {}
public Employee(int id,String name,Company company) {
this.name = name;
this.id = new EmployeeId(id,company.id);
this.company = company;
}
}
您可以使用Company
从持久性上下文中获取的find
实体。您也可以使用它的构造函数从头开始创建它。