简体   繁体   English

Java - 用于删除oneToMany关系的JPQL查询

[英]Java - A JPQL Query to delete a oneToMany relationship

If I have this 3 entities : 如果我有这3个实体:

@Entity public class Student { @Entity公共班学生{

 @Id @GeneratedValue(strategy=GenerationType.IDENTITY) protected Long id; private String name; 

} }

@Entity @Inheritance(strategy=InheritanceType.JOINED) public class Course { @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 { @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 ? 如何删除带有JPQL查询的学生?

I try 我试试

DELETE FROM Student s WHERE s.name = "John Doe" 删除学生的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_ID FOREIGN KEY ( students_ID ) REFERENCES student ( ID )) 无法删除或更新父行:外键约束失败( database ,CONSTRAINT FK_course_student_students_ID FOREIGN KEY( students_ID )REFERENCES studentID ))

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. 我需要在纯JPQL中执行此操作以获得性能,我无法执行entity.remove,因为我有10000个John doe,我需要在一秒钟内删除它们。

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 ! " 为什么JPQL没有说:“嘿,让我们从这个生物课程中删除这个john doe,他不存在”而不是“嘿,生物课程非常重要,没有学生可以从这门课程中删除!”

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... 编辑:添加@JoinColumn到OnToMany关系可以工作,除非学生被不同的表引用...

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: 如果您对使用join talbe没有任何特殊要求,可以在Student使用外键,它可以配置如下:

@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. 有时,您可以使用update all query清除对已删除对象的引用。

You can also configure you constraint on the database to cascade or null on delete to avoid constraint issues. 您还可以将数据库上的约束配置为在删除时级联或为空以避免约束问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM