During my interaction with several programmers, I came to know that many of them including experienced ones don’t know the meaning of transactions or we can say transactional behaviour. I am going to explain what is a transaction in the context of Spring/Grails.

By default, services in grails are transactional and it is where we implement most of the business logic that involves persisting data in the database. It means that a set of code meant to write something in database gets committed in the database all at once or nothing gets written to the database in case of failure.

We can also change the default transactional behaviour by using:


static transactional = false

We can declare it at the top of the class and then use @Transactional annotation which gives us flexibility to make only a particular method transactional in Service.

 

What is a transaction ?

A transaction is a sequence of operations(interacting with database) that is treated as a single unit for ensuring database integrity.

What is a failure in transaction ?

In terms of Grails, any Runtime exception thrown is considered as a failure. So, the transaction rolls back only when Runtime exceptions are thrown.

When a transaction is committed in the database?

A transaction will be committed once the last line of the code has been executed.

When will a transaction rollback ?

As mentioned earlier, if any Runtime exception is thrown, a transaction is rolled back.

Let me demonstrate that with an example:

class Tag {
String tagName
String description
static constraints = {
tagName(nullable: false)
description(nullable: false)
}
}

class TagService {

def saveTag() {
Tag tag=new Tag(tagName: "Mobile", description: "Some description...")
tag.save()

}

def saveTagWithRuntimeException() {
Tag tag=new Tag(tagName: "Apple", description: "Some description...")
tag.save()
println 1/0 // Runtime exception

}

def saveTagWithCheckedException() {
Tag tag=new Tag(tagName: "Laptop", description: "Some description...")
tag.save()
throw new NullPointerException() //Throwing Compiletime Exception
}
}

In the above example, transaction will be rolled back in “saveTagWithRuntimeException()” method and only 2 instances of tags will be saved.

This transaction management is handled by the Transactional Aspect of Spring. Here is a simple diagram to make the concept clear:

 

I hope that the concept of transactions was clear. You can comment on this post if you have any questions.

Keep reading and learning 😉