保存在afterInsert事件中时,对象不会持久存在

时间:2013-07-04 00:29:14

标签: 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")
         }else{
              println("ERROR")
          }

     }
  }

它打印“OK”,我甚至可以打印anotherDomain对象,一切似乎没问题,没有错误,没有,但是anotherDomain对象不会在数据库中持久存在

2 个答案:

答案 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更有意义。如果xy依赖于Domain的任何持久值属性,则可以从hibernate缓存中获取它们,而不是转到db。

答案 1 :(得分:1)

这里有同样的问题而且.withNewSession还不够。我推了.save(flush: true),一切都运转良好。

def afterInsert() {

    AnotherDomain.withNewSession {
        new AnotherDomain(attribute1: value1, attribute2: value 2).save(flush: true)
    }
}
相关问题