2011-09-23 106 views
1

我有两个表这样级联与JPA /休眠(的EclipseLink)

|  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] 

正如你所看到的,它应该插入一个新的人员记录后首先一个员工,但事实上不是这样,外键personId=0原因问题。你可以帮我吗?谢谢!

回答

2

使用继承时,您不需要@PrimaryKeyJoinColumn。它将自动为您管理。你确实需要有一个唯一的ID值。如果您打算使用序列生成,则需要将@GeneratedValue添加到该ID。

@Id 
    @GeneratedValue 
    @Column("id") 
    public int getId() { 
     return this.id 
    }