StaleObjectStateException on one domain object in a list affects all remaining updates

喜欢而已 提交于 2019-12-12 01:55:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!