Search code examples
grailsgrails-orm

Object not persisting when saved in afterInsert event


I have a domain class like this:

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

     }
  }

It prints "OK", I can even print the anotherDomain Object, and everything seems ok, no errors, nothing, but the anotherDomain Object doesn't persist in the database


Solution

  • You cannot persist the domain to database unless you try to save withNewSession.

    def beforeInsert(){
       def anotherDomain = new AnotherDomain()
         anotherDomain.x=1
         anotherDomain.y=2
    
        AnotherDomain.withNewSession{
           if(anotherDomain.save()){
               println("OK")
            }else{
                 println("ERROR")
            }
        }
      }
    }
    

    All events are fired when domain object is flushed to database. Existing session is used for the flush. The same session cannot be used to handle save() on another domain. A new session has to used to handle the persistence of AnotherDomain.

    UPDATE
    Using beforeInsert event makes more sense than afterInsert. If x and y are dependent of any persisted value property of Domain they can very well be fetched from hibernate cache instead of going to db.