连续两次保存的 Grails 唯一验证异常

Grails unique validation exception with two consecutive saves

让我们假设 nameid 是我的用户 table 上的唯一字段,并且我为两个都。因此,如果我有一个 id 2name "robel" 的值,为什么下面的代码给我验证异常?

User old = UserFindByName("robel")
old.setName("changed")
old.save(failOnError: true)
User neew = new User(name:"robel")
neew.save(failOnError: true)

我尝试设置断点并检查 old 的值在保存 neew 之前是否已更改,我确定它已更改但最后一行给我一个例外,说 name:"robel" needs to be unique .Why is this happening?

您应该 flush changes 在添加新实例之前。变化:

old.save(failOnError: true)

至:

old.save(failOnError: true, flush: true)