How to write Hibernate HQL query which remove all “grand children” elements?

徘徊边缘 提交于 2019-12-24 01:25:59

问题


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).


回答1:


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




回答2:


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
)



回答3:


Try this:

 String hql="delete from Student where group.school=:school";
 session.createQuery(hql).setParameter("school", schoolObject).executeUpdate();


来源:https://stackoverflow.com/questions/5299579/how-to-write-hibernate-hql-query-which-remove-all-grand-children-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!