Thursday, July 11, 2013

ensure rollback in grails services...RuntimeException

In grails it is advisable to have all your business logic(database updates) in a service method,so that when some goes wrong then a rollback is issued.

An example of the things that can go wrong is

  • A domain contraint is violated
  • An exception is thrown..caused by some weird thing or bad code
But you can also issue an explicit rollback. This is done by throwing an RuntimeException or any excepton that extends a RuntimeException.

Recently where I work, we tried to explicitly throw an Exception in a service, like so
throw

new Exception()

But a rollback was not issued because the exception thrown wasn't a RuntimeException.
It is paramount that a RuntimeException is thrown if you desire a rollback in your services.

Check if grails domain is dirty

Suppose you want to save a grails domain if it has been modified only. To get the list of dirty property name you will do this
objectInstance.dirtyPropertyNames