0

这个问题可能看起来有点令人困惑,所以我会尝试用例子来说明它。

我正在使用JPA 2.0Eclipselink 2.2

我有三个类PersonStudentCredentials有这种关系:

  • Student从 Person继承 ( extends )
  • 学生有凭据(@OneToOne

我的课程定义如下:

人.java

@Entity
@Table(name = "person")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING, length = 20)
@DiscriminatorValue("person")
public abstract class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String firstName;
    private String lastName;
    private String street;
    private String city;
    private String zipCode;
    private String phoneNumber;

    /*Getters and Setters*/

}

学生.java

@SuppressWarnings("serial")
@Entity
@Table(name = "student")
@DiscriminatorValue("student")
public class Student extends Person implements Serializable {

    @Column(unique = true)
    private String studentId;

    @OneToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval = true, optional = false, mappedBy = "student")
    @CascadeOnDelete
    private Credentials credentials;

    /*Getters and Setters*/
}

凭据.java

@SuppressWarnings("serial")
@Entity
public class Credentials implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(unique = true)
    private String username;

    private String password;

    private Student student;
}

问题是当我尝试删除学生时

        entityManager.getTransaction().begin();
        entityManager.remove(student);
        entityManager.getTransaction().commit();

出现此约束(我可以发布更多错误消息,但这似乎是关键):

jul 26, 2013 11:51:50 AM com.vaadin.Application terminalError
Grave: Terminal error:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`studentrecord`.`credentials`, CONSTRAINT `FK_CREDENTIALS_STUDENT_ID` FOREIGN KEY (`STUDENT_ID`) REFERENCES `person` (`ID`))
Error Code: 1451
Call: DELETE FROM person WHERE (ID = ?)
    bind => [36]
Query: DeleteObjectQuery(Alex)

我已经尝试了几种注释,一个方向,学生和凭据之间的双向关系,但结果几乎都是一样的。

如何删除学生实体?

任何帮助将不胜感激,在此先感谢。

4

0 回答 0