0

There is only a role per user in the application at the same time. To update a role, we previously remove all the current roles:

Integer roleId = params.roleSelector.toInteger()
def roleInstance = Role.findById(roleId)
UserRol.removeAll userInstance
UserRol.create userInstance, roleInstance

It is working, but I think it is more correct to perform removeAll and create as an unitary operation in order to a correct roll back if any error happens.

Is it possible?

UPDATE 1.

I found here that we can add @Transactional to make a method transactional. So if we write:

@Transactional
private def unitaryOperationUpdate {

    Integer roleId = params.roleSelector.toInteger()
    def roleInstance = Role.findById(roleId)
    UserRol.removeAll userInstance
    UserRol.create userInstance, roleInstance
}

If some error happened between removeAll and create, it would roll back correctly?

By the way, I'd like to know how to check myself if it is working: I asked that question in a separate thread: How to check if a @transactional method perform rollback correctly in Grails?

Community
  • 1
  • 1
chelder
  • 3,819
  • 6
  • 56
  • 90

1 Answers1

2

Services are the right place to do that, because they're already transactional. It means that if something goes wrong the transaction will be rolledback.

A side note is that only unchecked exceptions will rollback your transaction.

  • In my opinion, moving that code to a service would complicate the code innecesarely. Researching about transactional in controllers I found [here](http://stackoverflow.com/questions/2865055/spring-transactional-method-participating-transaction) that we can add @Transactional to make a method transactional. I updated my question (UPDATE 1) – chelder Aug 31 '13 at 12:04