service

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.

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

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 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.

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"])
    }
  • service.txt
  • Last modified: 2020/08/31 14:15
  • by chongtin