Bulk deletes/updates in hibernate: best approach?
I know in hibernate (or even in JPA?) bulk delete operations are not cascaded to related entities.
Let's assume you have following entities A, B and C.
B has a ManyToOne relationship with A but this is not inverted (so A does not 开发者_运维百科have a list of B's). C has a ManyToOne relationship with B but also this is not inverted (so B does not have a list of C's).Now, if an A gets deleted then I want all B's referencing this A to be deleted and all C's referencing these B's to be deleted as well. Since there is no cascading I need to propagate these deletes myself. So the question is what would be the best approach to go about this:
- sql (delete from C where b_id IN (select is from B where a_id in (select id from A ...
- using hibernate: load all C's for A and then delete those entities and then load all B's for A and delete those; finally delete A
- ???
I think HQL is the better option
You can use hibernate to execute native sql statements. For example you can write something like that:
session.createSQLQuery("delete from C where b_id IN (select is from B where a_id in (select id from A ...");
and you can check this guide Hibernate native SQL
精彩评论