How to join two unit operations (removeAll + create) into one

…衆ロ難τιáo~ 提交于 2019-12-12 01:58:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!