【问题标题】:Unpredictable "Could not synchronize database state with session" exceptions in grailsgrails 中不可预测的“无法将数据库状态与会话同步”异常
【发布时间】:2012-06-28 10:23:53
【问题描述】:

我开始在我的日志中看到“无法将数据库状态与会话同步”异常,我很难重现它。有时它工作得很好......我看到两个例外(它们发生在不同的时间):

ERROR JDBCExceptionReporter - 尝试获取锁时发现死锁; 尝试重新启动事务 ERROR PatchedDefaultFlushEventListener - 无法将数据库状态与会话同步 org.hibernate.exception.LockAcquisitionException:无法更新: [com.myapp.School#1911]

错误 PatchedDefaultFlushEventListener - 无法同步 带有会话 org.hibernate.StaleObjectStateException 的数据库状态: 行被另一个事务更新或删除(或未保存的值 映射不正确):[com.myapp.School#1905]

这是它们被抛出的方法:

def populateFriends(ArrayList<FriendView> friends, User user) {

    friends.eachWithIndex { friendView, index ->

        def friend = Friend.findByFriendId(friendView.id) ?: new Friend()
        def schoolName = friendView.schoolName
        def school = null
        if (schoolName) {
            school = School.findByName(schoolName) ?: new School(name: schoolName).save(flush:true)
        }
        if (school) {
            // add to user's school list
            user = User.get(user.id)
            user.addToSchools(school)
            user = user.merge(flush: true)
            user.save(flush: true)

            friend.school = school
        }
        friend.save(flush: true)
    }
}

我一整天都在做这件事,我非常感谢任何帮助。

【问题讨论】:

  • 你能在这里发布你的整个 School 域吗 - 2) 你为什么要做 user = user.merge(flush: true)
  • 你试过user.refresh()吗?当我遇到一些奇怪的行为时,我通常会参考这篇文章:stackoverflow.com/questions/536601/… 或更准确地说,答案是尝试保存。
  • 但是他真的应该尝试弄清楚为什么会发生这种情况以及问题的根源是什么,在我知道为什么会发生这种情况之前,我不会采取解决方法。
  • 这段代码在哪里“存在” - 在控制器、事务服务或什么中?完整的堆栈跟踪怎么样,或者至少是哪一行导致了异常?如何触发此代码 - 例如来自浏览器的单个请求、集成测试、多个同时请求?
  • 此代码在事务服务中。我已经缩小了问题的范围。似乎只有在多个同时请求命中该方法时才会引发这些异常。这有帮助吗?

标签: grails grails-orm


【解决方案1】:

这里的答案是使用 lock:true。

School.findByName(name, [lock: true])

【讨论】:

    【解决方案2】:

    尝试:

    User.withTransaction {
        ...
        user.save(flush:true)
        sessionFactory.currentSession.flush()
        sessionFactory.currentSession.clear()
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-27
      • 2017-06-18
      • 1970-01-01
      • 2013-07-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      相关资源
      最近更新 更多