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:
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?
I use H2 database engine.
(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
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:
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();
精彩评论