A different object with the same identifier value is already associated with the session a classic hibernate error

Source: Internet
Author: User
Tags sessions
a different object with the same identifier value is already associated with the session2009-03-04 09:24:00 Tags: object session [push to technical circle]

This problem, I assign the object to null, it is also very useful. In my system, the update is good, but the insertion is not useful. Before the change, is inserted easy to use, and the update is not used. It was a problem in the system, but the catch just caught, from but, did not print out the log, Finding the reason is hard to find. When you are in a high database, it is best to print out the information in the exception capture. Org.springframework.orm.hibernate.hibernatesystemexception:a different object With the same identifier value is already associated with the session:4443398, of class:com.onewaveinc.media.cms.entity . Syncimportfolder; Nested exception is net.sf.hibernate.nonuniqueobjectexception:a different object with the same identifier value was Alrea Dy associated with the session:4443398, of Class:com.onewaveinc.media.cms.entity.SyncImportFolder
Net.sf.hibernate.nonuniqueobjectexception:a different object with the same identifier value is already associated with T He session:4443398, of Class:com.onewaveinc.media.cms.entity.SyncImportFolder
At Net.sf.hibernate.impl.SessionImpl.doSave (sessionimpl.java:852)
At Net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier (sessionimpl.java:790)
At Net.sf.hibernate.impl.SessionImpl.save (sessionimpl.java:749)
At Org.springframework.orm.hibernate.hibernatetemplate$9.doinhibernate (hibernatetemplate.java:555)
At Org.springframework.orm.hibernate.HibernateTemplate.execute (hibernatetemplate.java:363)
At Org.springframework.orm.hibernate.HibernateTemplate.save (hibernatetemplate.java:552)
At Com.onewaveinc.media.cms.dao.impl.SyncFolderHibernateDao.insertHavaIndex (syncfolderhibernatedao.java:31)
At Com.onewaveinc.media.cms.manager.SyncFolderManager.doImportSyncFolder (syncfoldermanager.java:193)
At Com.onewaveinc.media.cms.manager.SyncFolderManager.insertHavaIndex (syncfoldermanager.java:107)
At Com.onewaveinc.media.cms.manager.SyncFolderManager.importSyncFolderList (syncfoldermanager.java:607)
At Com.onewaveinc.media.cms.web.SyncFolderImportAction.post (syncfolderimportaction.java:41)
At Com.onewaveinc.media.common.web.HttpMethodAction.execute (httpmethodaction.java:36)
At Org.apache.struts.action.RequestProcessor.processActionPerform (requestprocessor.java:421)
At Com.onewaveinc.media.web.struts.MediaRequestProcessor.processActionPerform (mediarequestprocessor.java:51)
At Org.apache.struts.action.RequestProcessor.process (requestprocessor.java:226)
At Org.apache.struts.action.ActionServlet.process (actionservlet.java:1164)
At Org.apache.struts.action.ActionServlet.doPost (actionservlet.java:415)
At Javax.servlet.http.HttpServlet.service (httpservlet.java:709)
At Javax.servlet.http.HttpServlet.service (httpservlet.java:802)
At Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (applicationfilterchain.java:237)
At Org.apache.catalina.core.ApplicationFilterChain.doFilter (applicationfilterchain.java:157)
At Org.ajaxanywhere.AAFilter.doFilter (aafilter.java:41)
At Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (applicationfilterchain.java:186)
At Org.apache.catalina.core.ApplicationFilterChain.doFilter (applicationfilterchain.java:157)
At Com.onewaveinc.appcommon.security.web.utils.SecurityFilter.doFilter (securityfilter.java:89)
At Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (applicationfilterchain.java:186)
At Org.apache.catalina.core.ApplicationFilterChain.doFilter (applicationfilterchain.java:157)
At Org.springframework.orm.hibernate.support.OpenSessionInViewFilter.doFilterInternal ( opensessioninviewfilter.java:174)
At Com.onewaveinc.media.common.web.SpringHibernateSessionFilter.doFilterInternal ( SPRINGHIBERNATESESSIONFILTER.JAVA:50)
At Org.springframework.web.filter.OncePerRequestFilter.doFilter (onceperrequestfilter.java:76)
At Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (applicationfilterchain.java:186)
At Org.apache.catalina.core.ApplicationFilterChain.doFilter (applicationfilterchain.java:157)
At Com.onewaveinc.media.web.struts.StrutsValidateFilter.doFilter (strutsvalidatefilter.java:38)
At Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (applicationfilterchain.java:186)
At Org.apache.catalina.core.ApplicationFilterChain.doFilter (applicationfilterchain.java:157)
At Com.onewaveinc.appcommon.utils.web.SetCharacterEncodingFilter.doFilter (setcharacterencodingfilter.java:168)
At Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (applicationfilterchain.java:186)
At Org.apache.catalina.core.ApplicationFilterChain.doFilter (applicationfilterchain.java:157)
At Org.apache.catalina.core.StandardWrapperValve.invoke (standardwrappervalve.java:214)
At Org.apache.catalina.core.StandardValveContext.invokeNext (standardvalvecontext.java:104)
At Org.apache.catalina.core.StandardPipeline.invoke (standardpipeline.java:520)
At Org.apache.catalina.core.StandardContextValve.invokeInternal (standardcontextvalve.java:198)
At Org.apache.catalina.core.StandardContextValve.invoke (standardcontextvalve.java:152)
At Org.apache.catalina.core.StandardValveContext.invokeNext (standardvalvecontext.java:104)
At Org.apache.catalina.core.StandardPipeline.invoke (standardpipeline.java:520)
At Org.apache.catalina.core.StandardHostValve.invoke (standardhostvalve.java:137)
At Org.apache.catalina.core.StandardValveContext.invokeNext (standardvalvecontext.java:104)
At Org.apache.catalina.valves.ErrorReportValve.invoke (errorreportvalve.java:118)
At Org.apache.catalina.core.StandardValveContext.invokeNext (standardvalvecontext.java:102)
At Org.apache.catalina.core.StandardPipeline.invoke (standardpipeline.java:520)
At Org.apache.catalina.core.StandardEngin.ve.invoke (standardengin.ve.java:109)
At Org.apache.catalina.core.StandardValveContext.invokeNext (standardvalvecontext.java:104)
At Org.apache.catalina.core.StandardPipeline.invoke (standardpipeline.java:520)
At Org.apache.catalina.core.ContainerBase.invoke (containerbase.java:929)
At Org.apache.coyote.tomcat5.CoyoteAdapter.service (coyoteadapter.java:160)
At Org.apache.coyote.http11.Http11Processor.process (http11processor.java:799)
At Org.apache.coyote.http11.http11protocol$http11connectionhandler.processconnection (Http11Protocol.java:705)
At Org.apache.tomcat.util.net.TcpWorkerThread.runIt (pooltcpendpoint.java:577)
At Org.apache.tomcat.util.threads.threadpool$controlrunnable.run (threadpool.java:683)
At Java.lang.Thread.run (thread.java:534)



A different object with the same identifier value is already associated with the session
A classic hibernate error: A different object with the same identifier value is already associated with the session XXXX
hibernate3.0 use merge () to merge the same object in two sessions
specifically to my own code is
public object GetDomain (object obj) {
Gethibernatetemplate (). Refresh (obj);
return obj;
}
public void Deletedomain (Object obj) {
obj = Gethibernatetemplate (). Merge (obj);
Gethibernatetemplate (). Delete (obj);
}


Resolves a different object with the same identifier value is already associated with the session error

I have encountered this error two times, has not found a good solution, the cause of the error is believed to be known, because in the same session in the Hibernate has two identical identities but different entities, when running Saveorupdate (object) This error will be reported when the operation is done. Oh, you may say, you say so without saying nothing different, I admit that, oh, I do not know why the specific cause of this error, otherwise it will not be a long time to solve, now, give a temporary solution, to the same as me, no way to find the source of the people a way to continue to carry out (of course, yes , but not from the cause.

In fact, to solve this problem is very simple, only need to do Session.clean () operation can be solved, but you have a clean operation after the Saveorupdate (object) operation, it is possible to quote "Found two Representations of same collection ", I've been looking for a lot of information, and there's no good explanation for this article, which helps Max [url]http://opensource.atlassian.com/projects/ Hibernate/browse/hhh-509[/url].

Finally, it can be solved by the Session.refresh (object) method, noting that Session.refresh (object) is not available when object is not already in the database Because the refresh is to hibernate the object from the session, if you do not have it, you will have an error, so you need to judge before you use Saveorupdate (object)

Of course, the easiest way to solve this problem is to use the merge () method with the hibernate inside itself. However, I still feel very uncomfortable with the very use of the software itself (and Saveorupdate (), Save (), update () when encountering problems.

Later I discovered that this error often occurs in One-to-many mappings and many-to-many mappings, so please be careful when using one-to-many and many-to-many mappings.


Hibernate Problems and treatment


1, a different object with the same identifier value is already associated with the session.

Error reason: There are two identical identities in the same session in Hibernate but different entities.

Workaround one: Session.clean ()

PS: If Saveorupdate (object) and other changes to the data state are performed after the clean operation, it is possible to quote "Found two representations of same collection" exception.

Workaround Two: Session.refresh (object)

PS: When object is not already in the database, you cannot use Session.refresh (object) because the method is to re-enter object from the hibernate session, if there is no object in session, It will be an error, so you need to judge it before you use Saveorupdate (object).

Workaround Three: Session.merge (object)

Ps:hibernate the inside of the method, recommended use.

2. Found two representations of same collection

Error reason: See 1.

Workaround: Session.merge (object)

The above two anomalies often appear in a one-to-many mapping and multiple pairs of multiple mappings


A different object with the same identifier value is already associated with the session
A classic hibernate error: A different object with the same identifier value is already associated with the session XXXX
hibernate3.0 use merge () to merge the same object in two sessions
specifically to my own code is
public object GetDomain (object obj) {
Gethibernatetemplate (). Refresh (obj);
return obj;
}
public void Deletedomain (Object obj) {
obj = Gethibernatetemplate (). Merge (obj);
Gethibernatetemplate (). Delete (obj);
}
==================== I'm a split line ===================
In fact, my solution is to rearrange obj, note that the red character part of the public Serializable Save (Object persistentobject) throws Daoexception {
try {

Session session = This.opensession ();
BeginTransaction ();
PersistentObject = Session.merge (PersistentObject);
Serializable id = session.save (persistentobject);
if (autocommit)
CommitTransaction ();
return ID;
catch (Hibernateexception ex) {
Log.error ("Fail to save PersistentObject", ex);
throw new Daoexception ("Fail to save PersistentObject", ex);
finally {
if (autoclosesession)
CloseSession ();
}
} http://chenying.blog.51cto.com/614874/134702



Http://www.blogjava.net/mose2006/archive/2007/08/20/138072.html met again: A different object with the same identifier value was already associated and the session this error I have encountered two times, has not found a good solution, the cause of the error I believe we all know, Because there are two identical identities in the same session in the Hibernate, but different entities.
At first, according to the internet said with Session.merge (Object) reported a mistake, may be not used well, switch to session.clear (); Session.update (user); so it's OK,
The method is:

Package org.springframework.orm.hibernate3.support;
...
public void Modifybymerge (user user) {
Session session = Gethibernatetemplate (). Getsessionfactory ().
Getcurrentsession ();
Session.clear ();
Session.update (user);
}
...
The project is in Spring + hibernate so you have to use Gethibernatetemplate (). Getsessionfactory (). Getcurrentsession () to the current session
http://wdmcln.javaeye.com/blog/154066

1 If you use the Hibernate 2, you need to get/load/query to the persisted object, assign a new attribute value, and then save/update/saveorupdate.
The above code is: You cannot new an object that has an OID in session, directly
Detail.setsubjectid (1000L);
Session.save (detail);
When Session.save () a persisted object, it is converted to an update call.

2) Use the merge method of Hibernate 3. Session.merge (Newdetail), it finds the persisted object in the session cache, assigns the properties of the new object, and then saves the persisted object in the original session.
If an object that is not in session or in the database is used in the merge method, it can also help you insert the record into the table, equivalent to the Save method.

The above is a simple example, the actual business may be after a complex operation, it is difficult to find out whether a new object in the session/database already exists. So the first way you need to know each of your object states, the second method is more general in Hibernate 3.

Attached hibernate Javadoc comments on the Session.merge () method:
Copy the state of the given object onto the persistent object with the same identifier. If There is no persistent instance currently associated with the session, it would be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association was mapped with cascade= "merge".

The semantics of this method is are defined by JSR-220.

nhibernate-difference between session. Merge and session. Saveorupdate?

Http://stackoverflow.com/questions/170962/nhibernate-difference-between-session-merge-and-session-saveorupdate

This is from section 10.7. Automatic State detection of the Hibernate Reference documentation:

Saveorupdate () Does the following:if the object is already persistent into this session, do nothing if another object assoc Iated with the session has the same identifier, throw a exception if the object has no identifier property, save () it if The object ' s identifier has the value assigned to a newly instantiated object, save () it if the object is versioned (by a <version> or <timestamp>), and the Version property value was the same value assigned to a newly instantiated O Bject, save () it otherwise update () the object

and merge () is very different:if there are a persistent instance with the same identifier currently and the SE Ssion, copy the state of the given object onto the persistent instance if there are no persistent instance currently Ated with the sessions, try to load it from the database, or create a new persistent instance the persistent instance is re Turned the given instance does not become and the session, it associated remains

You are should use Merge () If your are trying to update objects that were in one point detached from the session, especially if There might is persistent instances of those objects currently with the session. Otherwise, using Saveorupdate () in, the case would the result in a exception.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.