Java - A JPQL Query to delete a oneToMany relationship
If I have this 3 entities :
@Entity public class Student {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) protected Long id; private String name;
}
@Entity @Inheritance(strategy=InheritanceType.JOINED) public class Course {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) protected Long id; @OneToMany private List<Student> students; private String name;
}
@Entity @Inheritance(strategy=InheritanceType.JOINED) public class Group {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) protected Long id; @OneToMany private List<Student> students; private String name;
}
How can I delete students with a JPQL query ?
I try
DELETE FROM Student s WHERE s.name = "John Doe"
But I have
Cannot delete or update a parent row: a foreign key constraint fails (database
, CONSTRAINT FK_course_student_students开发者_Go百科_ID
FOREIGN KEY (students_ID
) REFERENCES student
(ID
))
I need to do this in pure JPQL for performance, I can't do an entity.remove, because I have 10000 John doe and I need to delete them in a second.
Why JPQL doesn't say : "Hey, let's remove this john doe from this biology course, he doesn't exist" instead of "Hey, the biology course is so important that no student can be remove from this course ! "
What I am missing and what sort of annotation I have to use ?
Thanks !
Edit : Add a @JoinColumn to the OnToMany relationship could work, unless the students are referenced by different tables...
By default unidirectional one-to-many relationship is mapped via join table. If you don't have any special requirements about using join talbe you can use foreign key in Student
instead, it can be configured as follows:
@OneToMany
@JoinColumn
private List<Student> students;
It also should solve your problem with constrain violation.
Sometimes you can clear the references to the objects being deleted in a deleted all using an update all query.
You can also configure you constraint on the database to cascade or null on delete to avoid constraint issues.
精彩评论