Tuesday, April 29, 2008

How to add transactions to your grails business logic

There are 3 common ways in which you can surround your existing groovy or java code with transactions support under grails framework:

1. grails 'service' classes are transactional by default.
As long as the following statement is included in your grail service class, all methods executed will be executed under ongoing transaction. If no transaction exists when entering the service method, a new one will be auto created.

boolean transactional = true

2. If you are working with one or more grails domain objects in your code, wrap the code in 'withTransaction' block against one of the domain objects.
Described in more detail here:
http://grails.org/doc/1.0.x/guide/single.html#5.6%20Programmatic%20Transactions

3. Manually access hibernate session and create transaction against the session. This of course is tedious way and would require you to handle any exceptions yourself.

def session = sessionFactory.getCurrentSession()

Transaction tx = session.beginTransaction()

<>

tx.commit()
or
tx.rollback()

at the end.

4. Use spring declarative transaction control. I personally haven't tried it with grails; if you have please free feel to comment.

No comments: