views:

67

answers:

3

Hi folks,

I have got almost the same problem like that user.

In my situation I load one entity from db, I convert this entity into a DataTransferObject, then I want to edit one attribute, after that I convert it back into an entityObject, then I update that entity and hibernate throws following error:

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

Apparently, the problem is that the object I retrieve from db has the same id as the one I want to update (like it should be) BUT those are not the same objects!

How to manage that? Thank you for help...

A: 

choose either one:

1 - you can close the session after loading the entity and open new session for update

2 - instead of creating new Entity for update, use the old one and edit it.

3 - detach your first entity from session - session.evict(myEntity)

mohammad shamsi
Thank you for your ideas but I don't want to close the session and my architecture doesn't let me update the old object (besides a lot of effort)
Sven
@Sven can you detach entity from session?
mohammad shamsi
doesn't work: javax.servlet.ServletException: org.hibernate.SessionException: Session is closed!
Sven
+2  A: 

Your problem is that the object you previously loaded still exists in you hibernate session. I see two ways to cope with that.

1.) tell the hibernate session to merge your modified object with the one in the session

session.merge(object)

2.) kick the old object out of the session before writing the updated object to the session. session.clear() might work.

deadsven
clear works for me, thank you
Sven
changed it to merge. should be right...
Sven
A: 

Beyond just calling clear() on the session, it sounds like you might have a problem with the way you are using Hibernate:

Apparently, the problem is that the object I retrieve from db has the same id as the one I want to update (like it should be) BUT those are not the same objects!

Do you mean to say that you have two distinct entities which have the same ID? If so, then you should find a different field that uniquely identifies different entities.

matt b
No they are the same logical objects/ the same entities but java gives them different object-id's
Sven
how are the `<id>`s generated? what scheme are you using?
matt b