如何将两个单元操作(removeAll + create)合并为一个 [英] How to join two unit operations (removeAll + create) into one

查看:91
本文介绍了如何将两个单元操作(removeAll + create)合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在同一应用程序中,每个用户只有一个角色。要更新角色,我们以前会删除所有当前角色:

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

它正在工作,但是我认为执行removeAll并将其创建为一个单一操作以更正确地回滚(如果发生任何错误)更为正确。

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.

有可能吗?

更新1

我在此处找到了我们可以添加@Transactional来使方法具有事务性。因此,如果我们这样写:

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
}

如果removeAll和create之间发生了一些错误,它将正确回滚吗?

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

顺便说一句,我想知道如何检查自己是否正常工作:我在另一个线程中问了这个问题:如何检查@transactional方法是否在Grails中正确执行了回滚?

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?

推荐答案

服务是正确的选择,因为它们已经具有事务性。

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.

这篇关于如何将两个单元操作(removeAll + create)合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆