Reputation: 13190
I have a situation whereby a thread can retrieve an object from the db, and edit it and when flush it I get a StaleObjectStateException because in the meantime another thread has edited the same object (Im using optimistic locking). I can see why it is happening but I cannot change this behaviour.
So what I try to do is retrieve the object again from the db and reapply the changes on the latest version but I get another StaleObjectStateException as soon as I do the retrieval before I've even changed anything, why is this ?
try{
songs = nextSongGroup.getSongs(session);
modifySongs(songs);
session.flush();
}
catch(StaleObjectStateException sobe){
songs = nextSongGroup.getSongs(session);
modifySongs(songs);
}
Upvotes: 0
Views: 513
Reputation: 11184
If you got this exception it's too late already. You need to throw away the session and get a new one. Any queries on the same session will result in the same exception.
Theoretically calling em.clear(); and rerunning the same query might help. I have never tried this though.
For me I usually present the user with an Oops page that has a retry button that runs his request again on a clean session.
Upvotes: 1