使用JPA / Hibernate(EclipseLink)进行级联插入

时间:2011-09-23 02:13:32

标签: hibernate jpa-2.0 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]

正如您所看到的,它应该在此之后首先插入一个新的Person记录,但实际上它没有,外键personId=0会导致问题。你能帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:2)

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

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