开发者

Bulk deletes/updates in hibernate: best approach?

开发者 https://www.devze.com 2023-02-12 22:18 出处:网络
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.

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:

  1. sql (delete from C where b_id IN (select is from B where a_id in (select id from A ...
  2. 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
  3. ???


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

0

精彩评论

暂无评论...
验证码 换一张
取 消