2

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

How about:

session.replicate(entity, ReplicationMode.OVERWRITE);

?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.