1. 程式人生 > >Could not synchronize database state with session org.hibernate.StaleObjectStateException: Row was u

Could not synchronize database state with session org.hibernate.StaleObjectStateException: Row was u

 這個異常不是一定出現的,是偶爾

https://stackoverflow.com/questions/25428852/

這是在stackoverflow 上面的大神答,親測,問題已解決

This exception is caused by the following

  • Ann reads a row
  • Bob reads the the same row
  • Bob updates the row
  • Ann attempts to update the row, but the attempt fails because Hibernate notices that it has been updated since Ann read it

It's very difficult to advise you what to do about this, because you haven't provided any contextual information, e.g. who or what is reading/updating the row. Here is some general advice:

If you don't care about this scenario, and would like Ann to be able to update the row even though it has been updated (by Bob) since she read it, just disable optimistic locking by adding the following to the relevant domain class

static mapping = {
    version false
}

Alternatively, you can check in your controller whether the row has been updated since Ann read it, and if so, show her the updated row, so she can re-apply her updates to the latest data. The check in the controller can be performed by storing the version no. (that Ann read) in a hidden form field. When Ann's update is submitted (with the hidden version no.), load the object from the database and check that the submitted version no. equals the version no. of the object loaded from the database. If the numbers are different, display the latest version of the row along with a message informing her about what has happened.

Of course, the suggestion above is only applicable if the row is being updated by users submitting forms. But as I said, your question doesn't include any context, and my crystal ball is low on battery