使用@EmbeddedId和@MapsId会导致插入NULL(不违反NULL约束) [英] Use of @EmbeddedId and @MapsId causes NULL inserted (NOT NULL constraint violation)
问题描述
使用以下代码
@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字段中.
When trying to persist or merge the Employee
Entity, we can see that a NULL
as attempted to be inserted into the company_id field.
如何避免插入 NULL
?
推荐答案
即使进行了连接,在创建新对象(不是从持久性上下文中获取)时, company
字段也将保留为空
.
Even with the wiring, when creating a new object (not fetched from the persistence context), the company
field will remain null
.
在创建新的 Employee
实体时,您需要确保还初始化 company
属性:
When Creating a new Employee
entity, you will need to assure that you also initialize the company
attribute:
@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;
}
}
您可以使用 find
从持久性上下文中获取的 Company
实体.您还可以使用其构造函数从头开始创建它.
The Company
entity you might acquire from the persistence context using a find
. You also can create it from scratch using it's constructor.
这篇关于使用@EmbeddedId和@MapsId会导致插入NULL(不违反NULL约束)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!