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

lui*_*eta 4 grails grails-orm

我有这样的域类:

 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")
          }

     }
  }
Run Code Online (Sandbox Code Playgroud)

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

dma*_*tro 7

除非您尝试保存,否则无法将域保留到数据库withNewSession.

def beforeInsert(){
   def anotherDomain = new AnotherDomain()
     anotherDomain.x=1
     anotherDomain.y=2

    AnotherDomain.withNewSession{
       if(anotherDomain.save()){
           println("OK")
        }else{
             println("ERROR")
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当域对象是flushed数据库时,将触发所有事件.现有会话用于刷新.同一会话不能用于处理save()另一个域.一个新的会话必须用来处理持久性AnotherDomain.

更新
使用beforeInsert事件比使用更有意义afterInsert.如果x并且y依赖于任何持久值属性,Domain它们很可能从hibernate缓存中取出而不是转到db.