1

Possible Duplicate:
Spring + Hibernate : a different object with the same identifier value was already associated with the session

I've loaded an object X from DB using hibernateTemplate find by id, then I get some attributes from that object and added it to another object Y from the same type which was also loaded by the same X id. Then when I tried to saveOrUpdate object Y, hibernate throws exception a different object with the same identifier value was already associated with the session, which I think means that object X is associated with that attribute in the same session, so Y can't be saved or updated and affect also that attribute.

How can I remove object X from session so it's no longer associated with that attribute

I tried to use merge instead of saveOrUpdate and it's working fine, but is it the same as saveOrUpdate? I mean can I depend on it to add new records or update them?

Community
  • 1
  • 1
Amr Faisal
  • 2,004
  • 6
  • 27
  • 36

2 Answers2

2

After a lot of tries, I found that using merge is the best approach to handle this effectively, and to take care of new instances to be saved I think best approach is to do this:

if (X.getId() != null) {
    return hibernateTemplate.merge(X);
} else {
    hibernateTemplate.saveOrUpdate(X);
}

So if it was a new instance to session it'll be done through saveOrUpdate, and if it's a duplicated instance for the same rows, it'll be handled using merge.

Ryan Tenney
  • 1,812
  • 3
  • 16
  • 29
Amr Faisal
  • 2,004
  • 6
  • 27
  • 36
0

Perhaps you can try session.evict().

Abhijeet Kashnia
  • 12,290
  • 8
  • 38
  • 50
  • i tried it already, but it's not working – Amr Faisal Jul 20 '10 at 12:02
  • Can you explain why you even need two references, X and Y, to the same object? I think hibernate guarantees that within a session, there can be only one in-memory representation of that object, so X and Y are referring to the same entity. I think you will have to remove one of the object references in your code, so either X or Y will have to go when you link your objcets together. My understanding: if you remove X using session.evict(), it will remove Y from hibernate's first level cache too. Guess that's why it is not working. But you can't remove X and not remove Y. – Abhijeet Kashnia Jul 20 '10 at 12:35
  • 3
    Ok in my case X has a set of Bs, and the presentation layer takes this set and add/update/remove Bs, when saving or updating i want to know which elements from this set removed so i load Y with same id of X and compare between both of them, and then updating X then trying to save it throws the problem – Amr Faisal Jul 20 '10 at 13:04