2011-06-06 93 views
0

我有validate()grails方法的問題,當我使用entity.validate()實體對象被持久化在數據庫上,但我需要驗證多個對象之前保存數據。如何在不保存的情況下使用validate()grails方法?

def myAction = { 
    def e1 = new Entity(params) 
    def ne1 = new EntityTwo(params) 

    // Here is the problem 
    // If e1 is valid and ne1 is invalid, the e1 object is persisted on the DataBase 
    // then I need that none object has saved, but it ocurred. Only if both are success 
    // the transaction should be tried 
    if(e1.validate() && ne1.validate()){ 
    e1.save() 
    ne1.save() 
    def entCombine = new EntityCombined() 
    entCombine.entity = e1 
    entCombine.entityTwo = ne1 
    entCombine.save() 
    } 
} 

我的問題是我不希望在驗證都成功之前保存對象。

回答

4

呼叫丟棄()在任何情況下不希望當作爲改變/弄髒它檢測自動持久:

if (e1.validate() && ne1.validate()){ 
    ... 
} 
else { 
    e1.discard() 
    ne1.discard() 
} 
+0

感謝您的迴應,但它沒有像我期望的那樣工作,如果您有其他建議,請使用grails 1.3.6。 – yecid 2011-06-06 20:26:56

+0

如果描述的解決方案不起作用,您可以嘗試在保存前使用命令對象驗證您的值。在你的情況下,命令對象看起來像你的域類一樣。驗證成功後,您可以將命令對象「複製」到所需的域類並保存。請參閱:http://grails.org/doc/latest/guide/single.html#6.1.10命令對象 – hitty5 2011-06-07 06:27:32

0

我找到了解決方案與withTransaction()方法,因爲丟棄()方法僅適用於更新案例。

def e1 = new Entity(params) 
def ne1 = new EntityTwo(params) 

Entity.withTransaction { status -> 
    if(e1.validate() && ne1.validate()){ 
    e1.save() 
    ne1.save() 
    def entCombine = new EntityCombined() 
    entCombine.entity = e1 
    entCombine.entityTwo = ne1 
    entCombine.save() 
    }else{ 
    status.setRollbackOnly() 
    } 
} 

因此,只有驗證成功時,通過其他方式回滾事務才能完成事務。

我等着這個信息可以幫助任何人。 關於所有! :) YPRA

相關問題