Create transients using formula in Grails

31 / Dec / 2010 by Uday Pratap Singh 1 comments

I would explain this through a use case of my own project.

A Program has many AdvertisingMaterial and we have subclasses of AdvertisingMaterial, FlashAd, ImageAd etc. The user wants the ability to filter the programs which had flashAds, imageAds etc. This required filtering on the basis of the class property that we have in the 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")

The only thing that we missed in this approach was, that we got 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 nonpersistent object then it might not be a good solution. Whereas you can do it the other way by creating 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)"
}

Hope it helps!

FOUND THIS USEFUL? SHARE IT

comments (1 “Create transients using formula in Grails”)

  1. Reiner Saddey

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

    BTW: What about

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

    Reply

Leave a comment -