我有这样的域类:
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”,我甚至可以打印anotherDomain对象,一切似乎没问题,没有错误,没有,但是anotherDomain对象不会在数据库中持久存在
答案 0 :(得分:7)
除非您尝试保存withNewSession
,否则无法将域保留到数据库。
def beforeInsert(){
def anotherDomain = new AnotherDomain()
anotherDomain.x=1
anotherDomain.y=2
AnotherDomain.withNewSession{
if(anotherDomain.save()){
println("OK")
}else{
println("ERROR")
}
}
}
}
当域对象为flushed
到数据库时,将触发所有事件。现有会话用于刷新。同一会话不能用于处理另一个域上的save()
。新会话必须用于处理AnotherDomain
的持久性。
<强>更新强>
使用beforeInsert
事件比afterInsert
更有意义。如果x
和y
依赖于Domain
的任何持久值属性,则可以从hibernate缓存中获取它们,而不是转到db。
答案 1 :(得分:1)
这里有同样的问题而且.withNewSession
还不够。我推了.save(flush: true)
,一切都运转良好。
def afterInsert() {
AnotherDomain.withNewSession {
new AnotherDomain(attribute1: value1, attribute2: value 2).save(flush: true)
}
}