这个问题可能看起来有点令人困惑,所以我会尝试用例子来表达。
我正在使用 JPA 2.0 和 Eclipselink 2.2
我有三个类人,学生和证书这两个关系:
我的课程定义如下:
Person.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*/
}
Student.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*/
}
Credentials.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)
我尝试过几次anotations,一个方向,学生和证书之间的双向关系,但结果总是相同。
如何删除学生实体?
任何帮助都会非常感谢,提前谢谢。