0

In my application, in one transaction there are some domain objects that I want to delete, and some to update:

       Advertiser.withTransaction {
        batch.each {  record ->
            if (recordsShouldBeDeleted(record))
                record.delete()
            else 
                record.save()
           }
        }

I know that some of them are a parent key to a different table, so I shouldn't be able to delete them. I want that for now, in the loop, if the record can not be deleted nothing should happen and I would take care of them later. But as it's now, the whole transaction fails because of one record.

Is there a way to know, before I try do delete the object, if I would be able to do so, then I would know not to try to delete these certain object although my recordsShouldBeDeleted return true? (something like validate() method that checks constrains?)

Or there is any other idea for the situation?

Thanks.

Dvora
  • 1,175
  • 1
  • 16
  • 26

1 Answers1

1

What I usually do is surround the code with a try / catch block and if the delete fails, do nothing. Maybe it's not the best approach, but I haven't found still a reason for not doing it this way.

Advertiser.withTransaction {
    batch.each {  record ->
        if (recordsShouldBeDeleted(record))
            try{
                record.delete()
            } catch (Exception e) {}
        else 
            record.save()
       }
    }
Eylen
  • 2,617
  • 4
  • 27
  • 42