Grails 圣杯&x27;假';唯一错误
我有以下域类(缩短版) 及 及 以下方法Grails 圣杯&x27;假';唯一错误,grails,groovy,Grails,Groovy,我有以下域类(缩短版) 及 及 以下方法 public TalkingThread removeAllComments(TalkingThread thread){ def commentsBuf = [] commentsBuf += thread.comments commentsBuf.each{ it.author.removeFromComments(it) thread.removeFromComments(it)
public TalkingThread removeAllComments(TalkingThread thread){
def commentsBuf = []
commentsBuf += thread.comments
commentsBuf.each{
it.author.removeFromComments(it)
thread.removeFromComments(it)
it.delete()
}
if(!thread.save()){
thread.errors.allErrors.each{
println it
}
throw new RuntimeException("removeAllComments")
}
return post
}
public addComments(TalkingThread thread, def commentDetails){
commentDetails.each{
def comment = contructComment(it,thread)
if(!comment.save()){
comment.errors.allErrors.each{ println it}
throw new RuntimeException("addComments")
}
thread.addToComments(comment)
}
return thread
}
有时我需要从TalkingThread中删除所有注释,并添加共享相同uniquehash的注释。所以我调用removeAllComments(..)方法,然后调用addComments(..)方法。这导致了一场灾难
Comment.uniqueHash.unique.error.uniqueHash,这是由假定已删除的注释和正在添加的“新”注释引起的
我应该脸红吗?也许我的域类有问题
编辑问题的展开
也许这是一个不同的问题,但我认为会话已经删除了所有关联和对象。因此,会话状态知道所有
TalkingThread
注释都已删除。当然,这并没有反映在数据库中。我还假设新注释的“保存”是有效的,因为这种“保存”与会话状态一致。但是,这样的“保存”将与数据库状态不一致。因此,我对grails如何根据会话和数据库状态验证对象的理解是有缺陷的!如果您能帮助了解会话和数据库状态的保存验证过程,我们将不胜感激 如果要从对话线程
中删除所有注释
,则可以使用Hibernate的级联行为
加
到TalkingThread
,然后可以调用comments.clear()
,然后调用thread.save()
,这将删除关联中的注释
有一个。通过执行
it.delete(flush:true)
,至少刷新:it.delete()
class Comment {
static belongsTo = [talkingThread:TalkingThread]
static hasOne = [author:CommentAuthor]
Long uniqueHash
static constraints = {
uniqueHash(unique:true)
}
}
class CommentAuthor {
static hasMany = [comments:Comment]
Long hash
String name
String webpage
}
public TalkingThread removeAllComments(TalkingThread thread){
def commentsBuf = []
commentsBuf += thread.comments
commentsBuf.each{
it.author.removeFromComments(it)
thread.removeFromComments(it)
it.delete()
}
if(!thread.save()){
thread.errors.allErrors.each{
println it
}
throw new RuntimeException("removeAllComments")
}
return post
}
public addComments(TalkingThread thread, def commentDetails){
commentDetails.each{
def comment = contructComment(it,thread)
if(!comment.save()){
comment.errors.allErrors.each{ println it}
throw new RuntimeException("addComments")
}
thread.addToComments(comment)
}
return thread
}
static mapping = {
comments cascade: 'all-delete-orphan'
}