开发者

How to use the validate() grails method without saving?

开发者 https://www.devze.com 2023-03-11 20:23 出处:网络
I have a problem with the validate() grails method, when I use entity.validate() the entity object is persisted on the database, but I require validate multiple objects before to save the data.

I have a problem with the validate() grails method, when I use entity.validate() the entity object is persisted on the database, but I require validate multiple objects before to save the data.

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()
  }
}

My problem is that I do not want the objects to be saved before both validations开发者_开发百科 are successful.


Call discard() on any instance don't want to be automatically persisted when it's detected as changed/dirty:

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


I found a solution with withTransaction() method, because the discard() method is applied only to update cases.

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()
  }
}

So the transaction is completed only if the validation is successfully, by other way the transaction is rolled back.

I wait that this info can be to help for any people. Regards to all! :) YPRA

0

精彩评论

暂无评论...
验证码 换一张
取 消