org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session

  Yesterday, in the process of using hibernate, when executing update of an object, this problem occurred. Later, I checked the Internet and said that the reason is:

  In the same session, if there is already an object in a persistent state (load in, etc.), now construct a new PO, which has the same persistent identifier as the previous persistent object. When updating, will throw this error.

 

  Then I checked the code, and there is indeed this problem: I manually created an object in the front, and the id was set in it, and then I did a check to check whether the experience value ranges overlap. This check needs to be All objects are looked up from the database, so

  If so, there are indeed two objects with the same persistent identifier (identifier) ​​in the session. Later, I changed the code logic of the verification, that is, after the verification of the object, I put the object remove:

 

  

 

  

 

  After adding, and then executing update, there is no such problem.

 

  To summarize:

  Under what circumstances does this problem occur :

  

1 User user1 = session.load(1 );  
 2 User user2 = new User();  
 3 user2.setId(1); // At this time, the ID is the same as user1   
4 user2.setUsername("lalala" );  
 5 session.update (user2); // this will throw an error

 

  Solution:

     1. Don't re-new an object, use the load object to change its value. For example, the above example operates directly on user1, and finally updates user1

    2. If it is hibernate3 or above, you can use the session.merge() method
    . 3. Remove the object with the same identity in the session (session.evict(user1)), so that it becomes an out-of-control state, and then user2 can update.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325323056&siteId=291194637