How is flush: true different from manually flushing the currentSession?

Viewed 927

I have a GORM object that I'm working with in an integration test. It has a beforeUpdate hook that keeps a history of the previous password hashes. The code looks something like this:

class Credentials {
    List passwordHistory = []
    String username
    String password

    static hasMany = [passwordHistory : String]

    def beforeUpdate() {
        // of course I'm not really storing plain-text passwords, but
        // this is just for illustration.
        if (isDirty('password')) { passwordHistory << password }
    }
}

In the integration test, I'm wondering why:

appUser.credentials.password = newPassword
appUser.save(flush: true)
sessionFactory.currentSession.flush()
AppUser.withNewSession {
    appUser = AppUser.get(appUser.id)
    appUser.credentials.empty // eagerly fetch the list while session is open
}
assert !appUser.credentials.passwordHistory.empty() // contains the previous password

works, but

appUser.credentials.password = newPassword
appUser.save()
sessionFactory.currentSession.flush()
AppUser.withNewSession {
    appUser = AppUser.get(appUser.id)
    appUser.credentials.empty // eagerly fetch the list while session is open
}
assert !appUser.credentials.passwordHistory.empty() // is empty

does not. The difference is the flush: true in the appUser.save() call. I thought the call to save() attached the object to the current session, but flushing the current session does not add the password to the passwordHistory list. What's really going on here?

2 Answers
Related