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?
In Hibernate, an entity can be removed from a database by calling the Session. delete() or Session. remove(). Using these methods, we can remove a transient or persistent object from datastore.
Subqueries. For databases that support subselects, Hibernate supports subqueries within queries. A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed.
The following are some of the reasons why HQL is preferred over SQL: Provides full support for relational operations. It is possible to represent SQL Queries in the form of objects in HQL which uses classes and properties instead of tables and columns. Return results as objects.
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With