Wednesday, March 19, 2008

You learn something new every day... on the Grails Mailing List

The Grails mailing lists are tremendous resources. Not only are they great for getting your questions answered by the helpful experts that never seem to sleep, but you can often learn something from someone else's question/answer.

For example, just the other day, I came across this very helpful post by Chris Chen that describes a simple way to deal with get methods in your domain class that don't have a corresponding set method (ie. calculated properties). If you try to do this without some extra code, you will get a PropertyNotFoundException. In the past I've usually handled this by renaming the method so it doesn't start with get, even though get might make the most sense. The alternative is to use a transients list, but that just doesn't seem right to me for this situation.

What Chris suggested was to dynamically type your get method. So, for example, if you have a Parent class which has a collection of Child and you want to find the oldestChild, you can do this:


class Parent {
...
static hasMany = [children: Child]

def getOldestChild(){
//logic here to get oldest child
}
}

That's all there is to it. Just use def instead of a static type. Now, as far as Grails is concerned you will have a property called oldestChild. It will even show up in the scaffolding. Hibernate, however will remain blissfully ignorant. Now that I've seen this it seems painfully obvious, but if I hadn't read Chris' answer in that post, I would have never thought of it on my own.

This is just one example, there are many others, so if you aren't signed up for the mailing list or at least perusing the archives, I would encourage you to get started today.

1 comment:

Daniel said...

The mailing lists contain so many great advices, G2One should hire someone to transfer this into the reference documentation.

Until then, we should just use this here to browse the mailing list more efficiently:

http://grails.markmail.org/