问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/18535717/how-to-join-two-unit-operations-removeall-create-into-one