During Hibernate development, org. hibernate. NonUniqueObjectException processing and deadobjectexception are encountered.
Today, I encountered an operation to update data in the project. I found that no error was reported in the code, but the data was not updated. So I spent most of my time looking for the problem, finally, I found that the exception was swallowed up directly when I tried (= !! Blood lessons )!
After troubleshooting, an exception org. hibernate. NonUniqueObjectException is thrown. Through repeated checks and the results of DU Niang, the following code error occurs:
Session session = HibernateSessionFactory.getSession(); session.getTransaction().begin(); try{ Query hql = session.createQuery("from News where idnews = :id"); hql.setParameter("id", news.getIdnews()); News n = (News) hql.list().get(0); news.setCreatetime(n.getCreatetime()); news.setTitle(n.getTitle()); news.setIslive(n.getIslive()); session.saveOrUpdate(news); return true; } catch(Exception e){ return false; } finally{ session.getTransaction().commit(); HibernateSessionFactory.closeSession(); }
It turns out that in the same session in Hibernate, if an object already has a persistent state (load in, etc.), a new PO is constructed, the persistence identifier is the same as that of the previous Persistent Object. This error is thrown during update. Thank you for choosing http://fatkun.com/2011/04/org-hibernate-nonuniqueobjectexception.html.
My solution is to use the incoming news object to set the obtained n object value.
The above link provides a solution
1. Do not use the load object to change the value of a new object.
2. If it is hibernate3 or later, you can use the session. merge () method.
3. Remove the object identified in the session (session. evict (user1) to render it unmanageable. Then user2 can be updated.