2016-07-07 84 views
0

我使用Grails 2.4.2和我的控制器更新方法有以下代码:的Grails:数据保存,即使我设置错误

@Transactional 
def update(ErtIncommingInvoice ertIncommingInvoiceInstance) { 

    if (ertIncommingInvoiceInstance == null) { 
     notFound() 
     return 
    } 

    // Concurrent-Update Test 
    if (ertIncommingInvoiceInstance.version != params.version as int) { 
     flash.warning = "Another user changed the record! (Concurrent Update Error)" 
     ertIncommingInvoiceInstance.errors.rejectValue("ertInfo", "concurrent.update.error") 
     respond ertIncommingInvoiceInstance.errors, view:'edit' 
     return 
    } 

即使在的情况下,检测到错误,并错误对象被设置并且方法流程不执行

ertIncommingInvoiceInstance.save flush:true, failOnError: true 

数据已经在数据库中改变了。 显示编辑视图,但不显示错误,仅显示闪光消息。

我在推理中的错误在哪里?

回答

2

在任何save之前,Grails都会调用validate,并覆盖您在errors对象中设置的任何内容。此外,在您的方法完成后,Grails将自动在您的对象上调用save。您应该对已更改但不希望保留的任何物件拨打discard(),或者使用withTransaction区块创建交易并手动将其回滚。

0

由于@Gregor彼得林说,我现在用下面的代码,以检查是否有并发更新,并从其他用户重新显示更改后的数据... ...:

@Transactional 
def update(ErtIncommingInvoice ertIncommingInvoiceInstance) { 

    if (ertIncommingInvoiceInstance == null) { 
     notFound() 
     return 
    } 

    // Concurrent-Update Test 
    if (ertIncommingInvoiceInstance.version != params.version as int) { 
     ertIncommingInvoiceInstance.discard() 
     ertIncommingInvoiceInstance = ErtIncommingInvoice.get(params.id) 
     ertIncommingInvoiceInstance.errors.reject("concurrent.update.error") 
     respond ertIncommingInvoiceInstance.errors, view:'edit' 
     return 
    }