0

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

kuceram
  • 3,795
  • 9
  • 34
  • 54

1 Answers1

1

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)
   }
}
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • This works! I was trying CarStateLogItem.withNewSession but obviously it didn't work because as I understand this is concerned with hibernate session. What I don't understand (because lack of my Spring Transaction knowledge) is why it worked from controller. Is it like when I have a transaction (i.e. service with transactional = true) the current transaction with association to MySQL is taken? – kuceram May 21 '13 at 14:29
  • Transaction in service layer is coupled with the `datasource` associated. I am quite sure you would have a MySQL datasource and not mongodb. – dmahapatro May 21 '13 at 14:35