简体   繁体   中英

Grails MongoDB doesn't save in afterUpdate

I'm trying to put some of my domain classes into the MongoDB using the mongoDB grails plugin. Some of the classes stays in MySQL. Everything works fine even the saving of domain class instances into the MongoDB (for example in service on controller code). However, If I try to save the instance from the afterUpdate() of certain not-mongoDB class it doesn't work. It doesn't throw any exception or whatever...

My not-mongoDB domain class:

class CarState extends AbstractCarState {

   ...

   def afterUpdate() {
      def logItemInstance = new CarStateLogItem(this.properties)
      logItemInstance.save(failOnError: true)
   }
}

MongoDB domain class:

class CarStateLogItem extends AbstractCarState {
   ObjectId id

   static mapWith = "mongo"

   ...
}

The weird thing is that if I run the afterUpdate() code from controller it saves into the MongoDB. Am I something missing? Or why I cannot save the instance?

Thanks for any advice, Mateo

I think you need to initiate a new transaction in order to save in mongodb. If you notice, the transaction for CarState will be of MySQL . In order to transact with mongodb from the afterUpdate event there has to be a new mongodb transaction. Try this.

def afterUpdate() {
   CarStateLogItem.withTransaction{status ->
       def logItemInstance = new CarStateLogItem(this.properties)
       logItemInstance.save(failOnError: true)
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM