I'm working with Hibernate 4, Struts2, to attempt the removal of an entity, the following exception was thrown:
org.hibernate.NonUniqueObjectException: a different object With the same identifier value was Already Associated With the session
I was reading and I thought I understood the problem, in fact the exception is quite descriptive; had more than one object with the same identifier in the session and this was problematic because Hibernate execute a transaction on a given subject and at some point the information from my two objects would not be consistent. I think hibernate says "hey I have an object in the session with this ID, but not the object I gave you."
I checked my code and understood the problem, however, in an article I read that getting the object just before attempting to delete solve the problem, and it was. I do not understand why that fix the problem, so I think I have not understood the reason for the exception.
I think that session.get(...) returns the object that had been previously extract, but I'm not sure.
The method is:
public void eliminarElemento(Elemento elemento) {
try {
session.beginTransaction();
//Elemento elementoPersistido = (Elemento) session.get(Elemento.class, elemento.getId());
session.delete(elemento);
session.getTransaction().commit();
} catch (HibernateException he) {
he.printStackTrace();
session.getTransaction().rollback();
throw he;
}
}
If I uncommented the line and try to delete the object that returns Session.get (...) the exception no longer occurs. Why? Thanks.