Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 703
RyanLynch Avatar asked Jun 27 '12 02:06

RyanLynch


2 Answers

The answer here is to use lock:true.

School.findByName(name, [lock: true])
like image 57
RyanLynch Avatar answered Nov 18 '22 05:11

RyanLynch


Try with:

User.withTransaction {
    ...
    user.save(flush:true)
    sessionFactory.currentSession.flush()
    sessionFactory.currentSession.clear()
}
like image 1
moskiteau Avatar answered Nov 18 '22 06:11

moskiteau