2016-07-07 40 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 
    } 
相關問題