When Hiberate is updated, the following error occurs: a different object with the same identifier value was already associated with the session, identifier
The Hibernate framework is used. The Service class has the following method:
1 public boolean saveOrUpdateTroop (TroopsInfo o, Boolean save) {2 if (save) {3 Map <String, Boolean> existeds = this. troopsDAO. getExisted (); 4 Boolean flag = existeds. get (o. getName (); 5 if (flag! = Null & flag) {6 return false; // there are emergency teams with the same name 7} 8 this. troopsDAO. saveOrUpdate (o); 9} else {// Update 10 TroopsInfo old = this. troopsDAO. findUniqueBy ("id", o. getId (); 11 if (old. getName (). equals (o. getName () {12 // synchronously update the personnel information to the emergency team 13 this. troopsDAO. saveOrUpdate (o); 14} else {// you need to check that the name is repeat 15 maps <String, Boolean> existeds = this. troopsDAO. getExisted (); 16 Boolean flag = existeds. get (o. getName (); 17 if (flag! = Null & flag) {18 return false; // an emergency team with the same name exists 19} 20 this. troopsDAO. saveOrUpdate (o); 21} 22 this. emergencyPersonDAO. updateEPerson (o. getId (), o. getName (), o. getContact (); 23} 24 25 return true; 26}
When the actual execution is performed, the following error will be reported in row 13th (jump to here according to the preceding conditions): a different object with the same identifier value was already associated with the session.
Solution: change it to the merge () method.
Cause: from the context, the data is retrieved (stored in session cache) in the database before saving, and then saved. According to the official documentation of hibernate, update is described as follows:
Update the persistent instance with the identifier of the given detached instance, if there is a persistent instance with the same identifier, an exception is thrown. Therefore, the above error is well explained.
Similarly, the merge method of hibernate is interpreted as: 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 will be loaded...
Another solution is refresh () or clean (), but other errors are reported, so it is not recommended.