Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate; HQL; why does the delete query not work, but select does?

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?

like image 529
Stefan Hendriks Avatar asked Jan 20 '10 14:01

Stefan Hendriks


People also ask

How do you delete in hibernate?

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.

Are subqueries supported in HQL?

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.

Why we use HQL instead of SQL?

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.

Can you explain query in hibernate?

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.


1 Answers

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.

like image 159
skaffman Avatar answered Nov 15 '22 04:11

skaffman