Table of Contents

Service

Grails service mainly handle the business logic passed from the controller, and database access. By adding a @Transcational annotation, it will be wrap all methods within that service in a transaction. In case of any exception, it will roll-back automatically so that the database will not be modified. The controller class must located at /grails-app/services/ directory.

Creating a Service

There are two ways to do so, and they are listed as follow:

In Grails Console

Assume we want to create a service called CatService. we do the following in the console:

grails create-service cat

You will find the new files in

Created grails-app/services/YOUR_PROJECT/CatService.groovy
Created src/test/groovy/YOUR_PROJECT/CatServiceSpec.groovy

CatService.groovy is the real deal, and CatServiceSpec.groovy if for unit test. Here is the code generated for the service:

import grails.transaction.Transactional

@Transactional
class CatService {

    def serviceMethod() {

    }
}

You can remove the def serviceMethod(){…} and add your own.

In Intellij IDEA Ultimate

In the Project tree, right click on the \grails-app\services directory, and than select New→Grails Service, and than type the name of service your want.

Work with Domain Object

Assume we have a Cat domain. We can do the following to obtains all cat objects.

    @Transactional(readOnly = true)
    List<Cat> getAllCats{
        return Cat.findAll([sort:"name", order:"asc"])
    }