如何在不保存的情况下使用validate()grails方法?
当我使用entity.validate()时,validate()grails方法有一个问题。entity对象被持久保存在数据库中,但我需要在保存数据之前验证多个对象如何在不保存的情况下使用validate()grails方法?,grails,persistence,validation,Grails,Persistence,Validation,当我使用entity.validate()时,validate()grails方法有一个问题。entity对象被持久保存在数据库中,但我需要在保存数据之前验证多个对象 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 pe
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()
}
}
我的问题是,我不希望在两次验证都成功之前保存对象。任何实例上的Call discard()都不希望在检测到已更改/脏时自动保存:
if (e1.validate() && ne1.validate()){
...
}
else {
e1.discard()
ne1.discard()
}
当检测到任何实例已更改/脏时,不希望自动持久化该实例上的Call discard():
if (e1.validate() && ne1.validate()){
...
}
else {
e1.discard()
ne1.discard()
}
我用withTransaction()方法找到了一个解决方案,因为discard()方法只应用于更新案例
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我找到了一个使用withTransaction()方法的解决方案,因为discard()方法只应用于更新案例
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感谢您的回复,但它并没有像我预期的那样工作。如果您有其他建议,请使用grails 1.3.6。如果所描述的解决方案不起作用,您可以尝试在保存之前使用命令对象验证您的值。在您的情况下,命令对象看起来与域类相同。成功验证后,您可以将命令对象“复制”到所需的域类中并保存它。请参阅:Command objects感谢您的响应,但它并没有像我预期的那样工作。如果您有其他建议,请使用grails 1.3.6。如果所描述的解决方案不起作用,您可以尝试在保存之前使用Command objects验证您的值。在您的情况下,命令对象看起来与域类相同。成功验证后,您可以将命令对象“复制”到所需的域类中并保存它。请参见:命令对象