« Return to Thread: Domain object retains erroneous properties when in a Service

Re: Domain object retains erroneous properties when in a Service

by daniel82 :: Rate this Message:

Reply to Author | View in Thread

Hi everybody

I had the same problem. I solved it by first calling hasErrors() and validate() on the object, before delegating it to the update service. If the object hasErrors or does not validate I am calling discard() on it and rendering the object with it's errors in the view.

This gets even more messy if you have nested objects - like a whole object tree - which you want to update:
http://jira.codehaus.org/browse/GRAILS-4492
Eager fetching solves this problem, but my test sometimes fails and sometimes not... although the webtest never failed. I guess it's a integration test problem.

Best Regards,
Daniel



mykol wrote:
hi all,
i've moved a lot of GORM calls to services instead of controllers. this is
due to the fact i need transactions that spans more than one domain class.
unfortunately, when erroneous properties are set to the domain class, they
get retained or saved. to illustrate:


*domain class:*

class Book
{
String title
 static constraints = {
title(blank: false)
}
}

service:

*service method:*

def update(book)
{
if(!book.hasErrors() || book.save())
{
//do something
}
else
{
throw new RuntimeException()
}
 ..
..

}

*controller method:*

def update = {
def book = Book.get(params['id'])
book.properties = params
 if(!book.hasErrors() && bookService.update(book)
        {
            ....
        }
        else

...
}



if the "title" i pass is blank, and invoke the update action, when i go to
"show" or "browse" actions, i see that the book's title is now blank.
although it did enter the "else" clause in the "update" action. but somehow,
the book retained the title property inserted to it.


verified that without the service, and putting just "if(!book.hasErrors() ||
book.save())" to the controller, this behavior is not seen.

am i doing anything wrong?

regards,
mykol

 « Return to Thread: Domain object retains erroneous properties when in a Service