【发布时间】:2016-03-30 17:03:19
【问题描述】:
我有Employee(父母)和Emp_Contacts(孩子)。只有Employee 类具有单向映射。
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table(name="EMPLOYEE")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Size(min=3, max=50)
@Column(name = "NAME", nullable = false)
private String name;
...
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "emp_id")
private Set<Emp_Contacts> contacts;
...getters and setters...
我的Emp_Contacts如下:
@Entity
@Table(name = "Emp_Contacts")
public class Emp_Contacts implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int emp_contact_id;
@NotNull
@Column(name = "emp_id")
private long emp_id;
....
DB 表对emp_contacts 上的emp_id 表没有空FK 约束。
- 如果我删除上述约束,那么
persist(employee)将保留员工和相应的 emp_contacts。 -
使用 FK 约束我得到以下错误:
MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
我在网上搜索,发现这个链接https://forum.hibernate.org/viewtopic.php?f=1&t=995514
但如果我在Employee 中输入可空值:
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "emp_id", nullable = false)
private Set<Emp_Contacts> contacts
我的服务器甚至没有启动,我收到以下错误:
Repeated column in mapping for entity: com.cynosure.model.Emp_Contacts
column: emp_id (should be mapped with insert="false" update="false")
我做错了什么?
【问题讨论】:
标签: java mysql hibernate spring-mvc foreign-keys