0

I have an hibernate object, transformed from a DTO, to delete. Because this object is not attached to the Session I can't just delete it, it will cause a NotUniqueObjectException, so I need to either merge it, or find the equivalent object in the Session. What is faster, to do Session.get() or Session.merge()?

Even better, is there a way of deleting an object without getting the managed object from the Session first?

Community
  • 1
  • 1
Niel de Wet
  • 7,806
  • 9
  • 63
  • 100

1 Answers1

0

merge() basically gets the object, then copies the state from the detached instance to the attached one, and applies cascades. So obviously, to get an object, get() is not only faster, but more appropriate.

You can get an attached instance without even querying the database by using session.load(), which returns an uninitialized proxy if the object isn't contained by the session yet.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Good to note that calling `delete()` with a proxy for an object that doesn't exist in the db will cause an `ObjectNotFoundException`, just like if you tried to access a property of the proxy. – Niel de Wet Apr 04 '14 at 13:11
  • [This answer](http://stackoverflow.com/a/608979/297331) is a nice explanation of the difference between `get()` and `load()`. – Niel de Wet Apr 04 '14 at 13:12