Possible Duplicate:
Spring + Hibernate : a different object with the same identifier value was already associated with the session
After changing the @id
of a Entity from
@Id
private int getId(){
return this.id;
}
to
@Id
private String getLogin(){
return this.login;
}
I get the error:
a different object with the same identifier
value was already associated with the session
In the webapplication isn't changed anything. A read the entity and then change some fields in a form and than after submit I tried to save or update the Entity. With the int
as @Id
there was no problem but now with the String
as @Id
I get the above error by update or save the Entity:
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void saveOrUpdate(User u) {
getHibernateTemplate().saveOrUpdate(u);
}
What could be the problem?
It means you are trying to save or update a detached object which has an un-unique or set auto-incrementing identifier.
If you want to insert a new object you want it's id to be empty or unique depending on whether you use auto incrementation or not(null for auto incrementation, set with a unique value for non-auto-incrementation), if you want to update it you want to make sure it is attached to the context.
You can reattach an object to the context using session.merge(object) which returns an attached version of the object.
In other words:
If you are trying to insert make sure the field that is configured as Id is either null if you use auto incrementation or is unique.
If you are trying to update make sure the object is attached. You can do this by selecting it from your database (based on the fields you have), make the changes, and then update, or just call the session.merge(object) method and receive an attached version of the object which you can then also update.