Search code examples
grailsgrails-orm

Unpredictable "Could not synchronize database state with session" exceptions in grails


I am starting to see "Could not synchronize database state with session" exceptions in my logs and I'm having a hard time reproducing it. Sometimes it works fine... I am seeing two exceptions (they are happening at different times):

ERROR JDBCExceptionReporter - Deadlock found when trying to get lock; try restarting transaction ERROR PatchedDefaultFlushEventListener - Could not synchronize database state with session org.hibernate.exception.LockAcquisitionException: could not update: [com.myapp.School#1911]

And

ERROR PatchedDefaultFlushEventListener - Could not synchronize database state with session org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.myapp.School#1905]

Here is the method where they are thrown:

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)
    }
}

I've been at this all day and I'd really appreciate any help.


Solution

  • The answer here is to use lock:true.

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