views:

56

answers:

2

Hi there,

my case is that, 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 i tried to saveOrUpdate object Y, hibernate thrown exception 'a different object with the same identifier value was already associated with the session' which means as i think 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

so how can i remove object X from session so it's no more associated to 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?

A: 

Perhaps you can try session.evict().

Abhijeet Kashnia
i tried it already, but it's not working
Amr Faisal
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
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
A: 

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

Amr Faisal