Grails 在afterInsert事件中保存时对象未持久化
我有这样一个域类:Grails 在afterInsert事件中保存时对象未持久化,grails,gorm,Grails,Gorm,我有这样一个域类: class Domain { String a int b String c ... def afterInsert(){ def anotherDomain = new AnotherDomain() anotherDomain.x=1 anotherDomain.y=2 if(anotherDomain.save()){ println("OK")
class Domain {
String a
int b
String c
...
def afterInsert(){
def anotherDomain = new AnotherDomain()
anotherDomain.x=1
anotherDomain.y=2
if(anotherDomain.save()){
println("OK")
}else{
println("ERROR")
}
}
}
它打印“OK”,我甚至可以打印另一个域对象,一切看起来都正常,没有错误,什么都没有,但是另一个域对象不会持久存在于数据库中除非您尝试使用newsession保存
,否则无法将域持久存在于数据库中
def beforeInsert(){
def anotherDomain = new AnotherDomain()
anotherDomain.x=1
anotherDomain.y=2
AnotherDomain.withNewSession{
if(anotherDomain.save()){
println("OK")
}else{
println("ERROR")
}
}
}
}
当域对象被刷新到数据库时,将触发所有事件。现有会话用于刷新。同一会话不能用于处理另一个域上的save()
。必须使用新会话来处理另一个域的持久性
更新
在插入前使用事件比插入后使用事件更有意义。如果x
和y
依赖于Domain
的任何持久值属性,则可以很好地从hibernate缓存中获取它们,而不是访问数据库。在这里也有同样的问题,只是。使用newsession
是不够的。我已经将.save(flush:true)
放好,一切正常
def afterInsert() {
AnotherDomain.withNewSession {
new AnotherDomain(attribute1: value1, attribute2: value 2).save(flush: true)
}
}
@luisZavaleta相反,我建议您在插入事件之前使用。