hibernate - Grails controller saves the domain item anyways -


using grails 2.3.9

in controller checks , when failing returning custom error response. here code snippet:

def update() {     def instance = group.get(params.groupid)     instance.properies = params      if (instance.haserrors()) {         // going through here: instance not saved         respond instance.errors, view:'edit'         return     }      // custom checks     if(checksfailed) {         // instance saved anyways :(         instance.discard()         response.senderror(response.sc_conflict)         return     }      instance.save flush:true     // ... respond success } 

when check fails, error response returned want it. however, instance gets saved anyways (the instance.save not reached). how can make grails/hibernate know not save instance?

another approach might disconnect instance hibernate session. how have in grails?

update: in controller domain instance scaffolded, instance.discard() trick works:

def update(group groupinstance) {     if (groupinstance.haserrors()) {         // going through here: instance not saved         respond instance.errors, view:'edit'         return     }      // custom checks     if(checksfailed) {         // instance not saved         groupinstance.discard()         response.senderror(response.sc_conflict)         return     }      groupinstance.save flush:true     // ... respond success } 

i find difficult understand why works in 1 case , not in another.

the best way not use discard() instead use transactions , native transaction features of database. recommend moving logic service (separating controller flow code , logic of application. example:

class groupservice {    @transactional    void updatebook(params) {        ....        // custom checks        if(checksfailed) {           status.setrollbackonly() // rollback transaction                }        else {            instance.save flush:true        }    } } 

you can either call setrollbackonly on transaction status or throw runtime exception.

note if use exceptions, can expensive best create custom exception type groupupdateexception , override fillinstacktrace not fill stack trace reduces cost of exception. see why throwable.fillinstacktrace() method public? why use it?


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -