为什么grails在返回后将我的对象保存到数据库

为什么grails在返回后将我的对象保存到数据库,grails,grails-2.0,Grails,Grails 2.0,我使用的是Grails2.4.5版本。我正在保存时检查一个条件。如果我的条件匹配,我将尝试返回一条消息,而不是保存。但它向我显示了我想要的消息,但同时它将对象属性保存到数据库中。有人能帮我吗?下面是我的代码: @Transactional def save(AccountHead accountHeadInstance) { if (!request.method.equals('POST')) { redirect(action: 'index') re

我使用的是Grails2.4.5版本。我正在保存时检查一个条件。如果我的条件匹配,我将尝试返回一条消息,而不是保存。但它向我显示了我想要的消息,但同时它将对象属性保存到数据库中。有人能帮我吗?下面是我的代码:

@Transactional
def save(AccountHead accountHeadInstance) {
    if (!request.method.equals('POST')) {
        redirect(action: 'index')
        return
    }
    LinkedHashMap result = new LinkedHashMap()
    String outPut

    if (accountHeadInstance.id) {
        if (accountHeadInstance.id == accountHeadInstance.subParentId) {
            result.put(CommonUtils.IS_ERROR, Boolean.TRUE)
            result.put(CommonUtils.MESSAGE, "Sorry, Same account can not be parent of it's  own")
            outPut = result as JSON
            render outPut
            return
            // here should it return, is shows the message ok but saving the object. if I print something after this block it does not execute
        }
    }

    if (accountHeadInstance.hasErrors()) {
        def errorList = accountHeadInstance?.errors?.allErrors?.collect{messageSource.getMessage(it,null)}
        result.put(CommonUtils.IS_ERROR, Boolean.TRUE)
        result.put(CommonUtils.MESSAGE, errorList?.join('\n'))
        outPut = result as JSON
        render outPut
        return
    }

    accountHeadInstance.hasChild = params.position == CommonUtils.POSITION_FIRST
    accountHeadInstance.save flush:true
    result.put(CommonUtils.MESSAGE, "Account head saved successfully.")
    outPut = result as JSON
    render outPut
    return
}

您使用的是@Transactional,所以对域对象的任何更改都会将该对象设置为dirty,并且当事务结束时,它们将被隐式保存。要防止出现这种情况,可以使用accountHeadInstance.discard()

然而,我不得不告诉您,您的代码是几个Grails反模式

任何业务逻辑,尤其是使用@Transactional的业务逻辑,都应该移动到服务中,而不是在控制器中完成。控制器应该只用于绑定传入参数、路由到服务和呈现结果

虽然可以将域用作命令对象绑定参数,但从安全角度来看,这通常不是一个好主意

您还可以选择执行如下“Groovy”操作:

LinkedHashMap result = [:]
result[CommonUtils.IS_ERROR] = Boolean.TRUE)
render result as JSON