3

I'm quite new to Hibernate and have a question. What is the difference between deleting an object by using an HQL query and deleting an object by using the delete(...) Method of the Session Class?

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
Patrick
  • 89
  • 2
  • 6

1 Answers1

3

Session.delete(...) is only useful if you already have a reference to the entity you want to delete.

delete-by-query is useful for deleting several objects according to certain criteria, objects that you may not have previously loaded into the session.

I believe that delete-by-query actually loads each entity into the session and deletes them individually - someone correct me if I'm wrong on this.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • But both make the targeted objects transient? – Patrick May 09 '11 at 13:12
  • @Patrick: If those entities have been previously loaded into the session, yes – skaffman May 09 '11 at 13:13
  • Two other Objects have references to the object i want to delete(In collections). Can Hibernate remove those references or do i have to do it by myself? – Patrick May 09 '11 at 13:18
  • 1
    It translates the query to native query and executes it. So not loading them I think. An important note is that it doesn't respect cascades – Bozho May 09 '11 at 15:05
  • I was referring to the answer (the final paragraph) – Bozho May 09 '11 at 16:00
  • "I believe that delete-by-query actually loads each entity into the session and deletes them individually " - I think that this is plainly wrong. This would mean that bulk deletions offer no improvement over select + delete in session. I also haven't seen this being mentioned in the hibernate user guide. – SpaceTrucker Feb 14 '16 at 08:20