Create transients using formula in Grails « Intelligrape Groovy & Grails Blogs

Create transients using formula in Grails

In one of my project where the domain was like.
A Program has many AdvertisingMaterial and we have subclasses of AdvertisingMaterial, FlashAd, ImageAd etc. The user want the ability to filter the programs which has flashAds, imageAds etc. Now I need to do the filtering on the basis of the class property that we have in database table (When table tablePerHierarchy is true). So I did some changes in my domain class to get this property.

class AdvertisingMaterial {
        String className

        static constraints = {
                className(nullable: true)
        }

       static mapping = {
               className formula: 'CLASS'
       }
} 

Now what I can use this className field in my dynamic finders and criteria query as well. So I can do something like

List<AdvertisingMaterial>adMaterials=AdvertisingMaterial.findAllByClassName("com.project.FlashAd")

Only thing that we miss in this approach is, we get the className property only with the persistent objects. If you do something like

FlashAd flashAd=new FlashAd()

and call flashAd.className then you will get null in it because the object is not persisted into the database yet. If you want your transient even with the non persistent object than it might not a best solution for you and you can do it other way where you create a transient property and its getter method.

This approach can be used in some other use-cases like

static mapping = {
               fullName formula: "CONCAT(FIRST_NAME,'  ',LAST_NAME)"
               totalAmount formula: "SUM(AMOUNT)"
}

This formula property is well defined in grails docs

Hope it helps
Uday Pratap Singh
uday@intelligrape.com
https://twitter.com/meudaypratap
http://in.linkedin.com/in/meudaypratap

This entry was posted on December 31st, 2010 at 10:12 am and is filed under Design Pattern, GORM, Grails . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “Create transients using formula in Grails”

  1. Nice one – was looking to access class property for ages. Thanks!

    BTW: What about

    String getClassName() {
    return className ?: getClass().getName()
    }

Leave a Reply