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
?
You can try handling transaction explicitly using @Transactional
annotation inside the service class.
Notes:-
@Transactional
annotation to service method, the service class is not deemed transactional by default.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.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(){
.......
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With