views:

182

answers:

2

I want to delete certain records from a table. These records have some child-records in other tables.

In order to be able to delete the main records, I have to delete the child records first.

Here is the example of the HQL used:

delete from ItineraryBooking ib where ib.booking.user.id = :paramId

Basically, this should remove all ItineraryBookings (records in seperate table), these are joined to the Booking table. A Booking table can be joined with the User table.

The odd thing is that when you change the above to:

from ItineraryBooking ib where ib.booking.user.id = :paramId

And execute a Query.list(), it will work just fine.

Whenever I want to execute the delete variant, it looks like Hibernate generates an odd delete statement. Is my HQL wrong? Or is it a Hibernate quirk?

+3  A: 

From the hibernate manual:

No joins, either implicit or explicit, can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the subqueries themselves may contain joins.

Your ib.booking.user.id clause looks like a join to me. I don't know if Hibernate actively rejects joins in a delete statement, or just silently gets it wrong.

A nicer way to delete child records is to use cascading deletes.

skaffman
Yes, you are correct, they are joines. I will look into the cascading deletes functionality, because I believe it *should* work like that, but it simply does not. There was a reason why the other related records had to be deleted explictely.Thanks for the answer!
Stefan Hendriks
A: 

Simple questions that may help:

  1. Just for curiosity, are you running this HQL in a transaction? selects doesn't need a transaction, but deletes does need it.

  2. Are you flushing the session after executing the deletion HQL?

  3. Are you deleting, and selecting in the same transaction or in separate ones?

Omar Al Kababji
1. The delete is in a transaction2. Yes3. Seperate transactions
Stefan Hendriks
May be you have some caching problems? I mean the data is deleted from the DB but is still present in the memory? try to flush the sessions before executing the queries too, may be that would help.
Omar Al Kababji