grails - how to call beforeDelete event when deleting many side element in a one-to-many association? -


i have 1 many association here both domain classes

purchaseorder

class purchaseorder {   bigdecimal balance    static constraints = {     balance nullbale:false   }    list items   static hasmany = [items:item] 

}

item

class item {   string product   integer quantity   bigdecimal price    def beforeinsert() {     def balance = purchaseorder.balance ?: 0      total = price * quantity     purchaseorder.balance = balance + total   }    def beforedelete() {     purchaseorder.balance -= total   }    static belongsto = [purchaseorder:purchaseorder] } 

in purchaseorder class field balance, field(balance) needs calculated when item object created or when updated or deleted.

beforeinsert event in item class called , update balance not case when when try delete item beforedelete not called

i trying delete item way

purchaseorderinstance.removefromitems iteminstance 

this way no error message , balance property not calculated

if try

iteminstance.delete(flush:true) 

i error message

error initializing application: deleted object re-saved cascade (remove deleted object associations): [ni.sb.item#2]; nested exception org.hibernate.objectdeletedexception: deleted object re-saved cascade (remove deleted object associations): [ni.sb.item#2] 

i hope can me

it not work this. delete() item purchase must do

purchase.removefromitems (item) item.delete () 

problem removefromitems() clear belongsto reference , deletebefore() event fail.

another problem approach is, long purchase not saved , doing balance, balance wrong.

the easiest way make work recalculate balance on each access:

class purchase {     bigdecimal balance      bigdecimal getbalance () {         bigdecimal total = 0         items.each { item item ->             total += item.total ()         }         total     }      list items     static hasmany = [items:item] }   class item {     string product     integer quantity     bigdecimal price      bigdecimal total () {         price * quantity     }      // rest of code ... } 

i recommend read gorm gotchas.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -