The question may seem a little bit of confusing so I'll try to bring it on with examples.
I'm working with JPA 2.0 and Eclipselink 2.2
I've got three classes Person, Student and Credentials wich have this relationship:
- Student inherits (extends) from Person
- Student has credentials (@OneToOne)
My classes are defined as the following:
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;
}
The problem is that when I try to delete a Student
entityManager.getTransaction().begin();
entityManager.remove(student);
entityManager.getTransaction().commit();
This constraint appears (I can post more of the error message but this seems to be the key):
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)
I've tried several anotations, one direction, bidirectional relationship between Student and credentials but the result is pretty allways the same.
How can I delete the Student entity?
Any help would be much appreciated, thanks in advance.