2

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.

SerchRac
  • 171
  • 1
  • 12
  • have you tried `session.delete(session.get(Elemento.class, elemento.getID()));` ¿? If you can delete like this, then you have a problem with an already open object in the same session... – Alex S. Diaz Aug 18 '15 at 21:22
  • @AlexandroSifuentesDíaz Yes, maybe I forget to say that now it's working fine, but really don't know the reason. "_I think that session.get(...) returns the object that had been previously extract, but I'm not sure._" this idea is correct? thanks. – SerchRac Aug 19 '15 at 00:01
  • what do you mean by *extract* ? – Alex S. Diaz Aug 19 '15 at 00:06
  • which it has already obtained. – SerchRac Aug 19 '15 at 05:53
  • Possible duplicate of [Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session](https://stackoverflow.com/questions/1074081/hibernate-error-org-hibernate-nonuniqueobjectexception-a-different-object-with) – Vadzim May 16 '19 at 20:16

0 Answers0