Create transients using formula in Grails
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.
[java]
class AdvertisingMaterial {
String className
static constraints = {
className(nullable: true)
}
static mapping = {
className formula: ‘CLASS’
}
}
[/java]
Now what I can use this className field in my dynamic finders and criteria query as well. So I can do something like:
[java]
List<AdvertisingMaterial>adMaterials=AdvertisingMaterial.findAllByClassName("com.project.FlashAd")
[/java]
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:
[java]
static mapping = {
fullName formula: "CONCAT(FIRST_NAME,’ ‘,LAST_NAME)"
totalAmount formula: "SUM(AMOUNT)"
}
[/java]
Hope it helps!
Nice one – was looking to access class property for ages. Thanks!
BTW: What about
String getClassName() {
return className ?: getClass().getName()
}