Stijn Geukens
Stijn Geukens

Reputation: 15628

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:

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

Upvotes: 1

Views: 1766

Answers (2)

Feras Odeh
Feras Odeh

Reputation: 9306

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

Upvotes: 1

nidhin
nidhin

Reputation: 6920

I think HQL is the better option

Upvotes: 2

Related Questions