问题
I have a Quartz job in Grails that iterates my users and do a nightly update on each user. However, if I get a StaleObjectStateException on an update of a user object, it seems every update after that gets the same StaleObjectStateException. Something like this:
def users = User.list()
users.each { user ->
try {
user.doUpdate()
user.save()
} catch (all) {
// I end up here for every user object after a StaleObjectStateException
}
}
How can I recover? I don't mind sporadic failures (ideally I collect these and try again at the end), but now this literally stops all remaining updates.
回答1:
Ideally you should be doing each update/save in a new transaction, otherwise any failures will effect the entire transaction / hibernate session. This makes better sense since each update/save should be it's own atomic operation anyway.
You should also get each domain object inside the transaction.
def userIds = User.withCriteria {
projections {
property("id")
}
}
userIds.each { userId ->
User.withTransaction {
try {
def user = User.get(userId)
user.doUpdate()
user.save()
} catch (all) {
// do whatever.
}
}
}
来源:https://stackoverflow.com/questions/27878087/staleobjectstateexception-on-one-domain-object-in-a-list-affects-all-remaining-u