Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new transaction within existing transaction in Grails

I have Machine and Parts domain class

In my service class I am trying to start a transaction, inside that transaction i want to create a new transaction and commit it when it comes out of the inner transaction.

Machine.withTransaction { // transaction 1
    // some code to add Parts

    // some code to remove Parts
    Machine.withNewTrasaction { // transaction 2
       // some code to remove Parts.
    } // end of transaction 2

// some code to update couple of columns in machine table.
}// end of transaction 1

When it comes out of transaction 2 I want transaction 2 be commited the Parts for the Machine irrespective to transaction 1.But grails is throwing an error back as "Illegal attempt to associate a collection with two open sessions" How to commit the transaction 2 alone separately without considering the transaction 1?

like image 628
user2001627 Avatar asked Nov 13 '22 01:11

user2001627


1 Answers

You can try handling transaction explicitly using @Transactional annotation inside the service class.

Notes:-

  • Once you add @Transactional annotation to service method, the service class is not deemed transactional by default.
  • Since you splitting the functionality into two methods, you have to use the proxied instance of the service class to call the second method otherwise you cannot create a new transaction for the second method. Hence, use of applicationContext below in method 1.
  • You would not need withTransaction or withNewTransaction block any more.

Service class would look like:

class MachineService{
   @Transactional
   def someMethodToAddParts(){
       ......
       grailsApplication.mainContext.machineService.someMethodToRemoveParts()
       ......
   }

   @Transactional(propagation = TransactionDefinition.PROPAGATION_REQUIRES_NEW)
   def someMethodToRemoveParts(){
     .......
   }
}
like image 64
dmahapatro Avatar answered Nov 15 '22 05:11

dmahapatro