我有一个GORM对象,在集成测试中使用。它有一个beforeUpdate
钩子,用于保存上一次密码哈希的历史记录。以下是示例代码:
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 }
}
}
在集成测试中,我想知道为什么:
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
运作正常,但是
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
没有,区别在于appUser.save()
调用中的flush: true
。我以为对save()
的调用会将对象附加到当前会话,但刷新当前会话并不会将密码添加到passwordHistory
列表中。这里实际发生了什么?
get()
改成findById()
会发生什么? - user800014passwordHistory
的默认初始化器(... = []
)可能会让事情变得混乱。尝试将其删除。当然,您还需要更改向列表添加元素的方式。 - AndrewaddToPasswordHistory(...)
而不是直接附加,行为是否会改变(尽管我立即不确定原始集合是否支持addTo
...) - Andrew