tags:

views:

1379

answers:

3

Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?

  • Doing session.contains(obj) seems to only return true if the session contains that exact object, not another object with the same ID.
  • Using merge(obj) throws an exception if the object is new
+2  A: 

Have you tried calling .SaveOrUpdateCopy()? It should work in all instances, if there is an entity by the same id in the session or if there is no entity at all. This is basically the catch-all method, as it converts a transient object into a persistent one (Save), updates the object if it is existing (Update) or even handles if the entity is a copy of an already existing object (Copy).

Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your "new" object. This should be easy enough to do:

IPersistable entity = Whatever(); // This is the object we're trying to update
// (IPersistable has an id field)
session.Evict(session.Get(entity.GetType(), entity.Id));
session.SaveOrUpdate(entity);

Although the above code could probably do with some null checking for the .Get() call.

Quibblesome
A: 

I'm going to have to try saveOrUpdateCopy - thank you! Will it work if there is nothing in the session?

I would like to .evict the object, but can't seem to find any way to identify it since session.evict will only evict that exact object, not the other object in the session with the same identifier

+1  A: 

How about:

session.replicate(entity, ReplicationMode.OVERWRITE);

?

Georgy Bolyuba