grailsgrails-ormgrails-2.0grails-domain-classgrails-controller

How can I isolate a single delete(..) from being rolled back during runtime exception in grails 2.5.6?


I am working on a legacy grails 2.5.6 project.

As part of the logic, an exception(type of RuntimeException) is thrown when an orphaned record is detected. While doing so, the orphaned record has to be deleted. This logic is deep inside layers of service method calls which are in a big transactional block (by default).

Here is a sample code:

...
financialTransactionItem.delete(flush:true); /* flush: true is for a reason here */
throw new ServiceException(...);
...

But, obviously, the delete is rolled back when the ServiceException(derived from RuntimeException) is thrown and the orphaned record (financialTransactionItem) stays there.

The rollback is still necessary, as there are other DB transactions that must be discarded.

My question is: How can I do both? i.e. Rollback everything except the specified delete operation?


Solution

  • I enclosed the delete statement inside a withNewTransaction(...) block and the rollback didn't affect the delete operation.

    FinancialTransactionItem.withNewTransaction {TransactionStatus status ->
    
        FinancialTransactionItem obsoleteFinancialTransactionItem = FinancialTransactionItem.get(ftiItemId);
    
        if(obsoleteFinancialTransactionItem){
    
            obsoleteFinancialTransactionItem.delete(flush: true);
        }
    }