2011-06-06 68 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

相关问题