Cascade insert with JPA/Hibernate (EclipseLink)
I have two tables like this
| PERSON | | EMPLOYEE |
| id | fullName | | personId | code |
EMPLOYEE.personId
is a primary key as well as foreign key pointing to PERSON.id
I have these two classes:
@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 {
pr开发者_如何学编程ivate String code;
public Employee(String code) {
setCode(code);
}
@Column("code")
public String getCode() {
return this.code
}
public void setCode(String code) {
this.code = code;
}
}
And when I wanna insert a new record into EMPLOYEE table:
entityTransaction.begin();
Employee emp = new Employee("EMP001");
emp.setFullName("hiri");
this.entityManager.persist(emp);
entityTransaction.commit();
It throws an exception says:
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]
As you can see, it is supposed to insert a new Person record first an Employee after that, but in fact it doesn't, the foreign key personId=0
causes the problem. Can you help me? Thanks!
You do not need @PrimaryKeyJoinColumn when using Inheritance. It will be managed for you automatically. You do need to have a unique ID value though. If you intend to use sequence generation you need to add @GeneratedValue to the id.
@Id
@GeneratedValue
@Column("id")
public int getId() {
return this.id
}
精彩评论