Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to bulk delete from a many-many association with HQL?

And if so, what is the syntax?

Assume that I want an instance of Foo to be unassociated from all instances of Bar: In SQL it would simply be:

delete from FOO_BAR_MAPPING
where FOO_ID = ?

In HQL, I assumed it would be something like:

delete from Bar.foos foos
where foos.id = :id

(where foos is a mapped collection of Foo)

But appears to be wrong, giving:

org.hibernate.hql.ast.QuerySyntaxException: Bar.foos is not mapped

Is this even possible with HQL?

like image 394
ireddick Avatar asked Jul 29 '09 17:07

ireddick


1 Answers

To answer your specific question, no, as far as I'm aware it's not possible with HQL.

I think you're mixing SQL and HQL a little bit here. In SQL, you indeed "delete" records, and of course hibernate will ultimately do that as well. However Hibernate/HQL is designed from an object-oriented mindset, so "delete" in this context means you are deleting objects, not associations. Typically you'd do something like follows:

Foo f = session.get(Foo.class, id);
f.getBars().clear();
session.merge(f);

This retrieves the object by the id you specified, and removes all Bar associations by clearing it's collection. Obviously you have to have the Foo-Bars association mapped in the proper direction for this to work.

like image 183
Matt S. Avatar answered Sep 29 '22 07:09

Matt S.