【发布时间】:2011-11-23 07:51:52
【问题描述】:
我有两张这样的桌子
| PERSON | | EMPLOYEE |
| id | fullName | | personId | code |
EMPLOYEE.personId 是指向PERSON.id 的主键和外键
我有这两个类:
@Entity
@Table(name="PERSON")
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Person
implements Serializable {
protected int id;
protected String fullName;
@Id
@Column("id")
public int getId() {
return this.id
}
public void setId(int id) {
this.id = id;
}
@Column("fullName")
public int getFullName() {
return this.fullName
}
public void setId(int fullName) {
this.fullName = fullName;
}
}
@Entity
@Table(name="EMPLOYEE")
@PrimaryKeyJoinColumn(name="personId")
public class Employee extends Person
implements Serializable {
private String code;
public Employee(String code) {
setCode(code);
}
@Column("code")
public String getCode() {
return this.code
}
public void setCode(String code) {
this.code = code;
}
}
当我想在 EMPLOYEE 表中插入一条新记录时:
entityTransaction.begin();
Employee emp = new Employee("EMP001");
emp.setFullName("hiri");
this.entityManager.persist(emp);
entityTransaction.commit();
它抛出一个异常说:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (...)
Error Code: 1452
Call: INSERT INTO EMPLOYEE (code, personId) VALUES (?, ?)
bind => [EMP001, 0]
如您所见,它应该先插入一个新的 Person 记录,然后再插入一个 Employee,但实际上并没有,外键 personId=0 导致了问题。你能帮助我吗?谢谢!
【问题讨论】:
标签: hibernate jpa-2.0 eclipselink