[英]How to write Hibernate HQL query which remove all “grand children” elements?
I have schools, which contains groups, which contains students. 我有学校,其中包含团体,其中包含学生。
I would like to remove all students from specific school. 我想将所有学生从特定学校中删除。
In SQL I can write the following query: 在SQL中,我可以编写以下查询:
DELETE FROM students1
WHERE students1.group_id IN
(SELECT id FROM group1 WHERE group1.school_id = :school_id)
How to transform this SQL query to Hibernate HQL? 如何将此SQL查询转换为Hibernate HQL?
I use H2 database engine. 我使用H2数据库引擎。
(My real query is more complex and simple cascade deletion of school is not suitable for me). (我真正的查询更复杂,简单的级联删除学校不适合我)。
The working script follows: 工作脚本如下:
DELETE FROM Student AS s
WHERE s IN
(SELECT s FROM Student AS s WHERE s.group IN
(SELECT g FROM Group AS g WHERE g.school IN
(SELECT s FROM School s WHERE s.id = :schoolId)))
Thanks to comments of doc_180 感谢doc_180的评论
You can't use JOIN
(either explicit or implicit) in Hibernate's bulk queries (like deletes) currently, but you can use them in subqueries, something like this: 当前,您不能在Hibernate的批量查询(如删除)中使用
JOIN
(显式或隐式),但可以在子查询中使用它们,如下所示:
DELETE FROM Student st
WHERE st IN (
SELECT st
FROM School s JOIN s.groups g JOIN g.students st
WHERE s = :s
)
Try this: 尝试这个:
String hql="delete from Student where group.school=:school";
session.createQuery(hql).setParameter("school", schoolObject).executeUpdate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.