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

后端 未结 2 1349
难免孤独
难免孤独 2021-01-12 06:18

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          


        
相关标签:
2条回答
  • 2021-01-12 07:11

    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.

    0 讨论(0)
  • 2021-01-12 07:22

    Removing associations alone is not possible with HQL. What you can do, however, is either:

    A) Assuming you're doing it for a single Foo and your cascade is set appropriately, you can load that Foo instance, clear its collection of bars and save it.

    B) If you're trying to clear bars from multiple Foos you can map an SQL query instead of HQL

    0 讨论(0)
提交回复
热议问题