Hibernate: Exception Handling with Duplicate Object Identifiers
The error message "Hibernate: different object with the same identifier value was already associated with the session" occurs when Hibernate encounters an object with an existing identifier that is already associated with the current session. This can arise when attempting to save or update an object that is already present in the session, resulting in a conflict.
In the provided code:
<code class="java">public E save(E e) { Session session = null; try { session = sessionFactory.openSession(); log.debug("session="+session.hashCode()+" save "+e); session.saveOrUpdate(e); //here throws exception session.flush(); } catch (Exception e1) { log.err("Cannot open hibernate session "+ e1.getMessage()+" cause : "+e1.getCause()); e1.printStackTrace(); } finally { if ( session != null ) session.close(); session = null;} return e ; }</code>
The exception is thrown when trying to saveOrUpdate a user bean. The cause of the problem appears to be that the user bean contains a list of group beans, which in turn have list of roles. When saving the user bean, Hibernate attempts to save the roles twice: once as part of the group beans and again as part of the user bean's role list.
userbean#1 |---|-----------***userbean.groups | | groupbean#1 | | groupbean.roles | | rolebean#1 # save relebean#1 the first time | | ---done rolebean#1 | | ------done all rolebeans of group.roles | | ---done groupbean#1 | |-----------done all groupbeans of userbean.groups |---|-----------***userbean.roles | rolebean#1 # save rolebean#1 the second time, and throws exception here! | ----done rolebean#1 | ..... |-----------done all rolebeans of userbean.roles
To resolve this issue, consider the following approaches:
The above is the detailed content of Why does Hibernate throw the \'different object with the same identifier value was already associated with the session\' exception when saving a user bean with nested collections, and how ca. For more information, please follow other related articles on the PHP Chinese website!