Wednesday, January 28, 2009

Grails Tips Part I – Domain Classes

I have been working a lot with Grails lately and I have to say that I love it!

It has allowed me to create some great web applications in a very fast and reliable way. While developing these applications, I learned a lot of useful things that I would like to share to you. Today I’ll give you some tips regarding Domain Classes.

1) Date created & Last Updated

If you want Grails to handle the date in which an object is created and the last time it was updated, all you have to do is add the following attributes to your domain class:

Date dateCreated
Date lastUpdated

As easy as that! Grails will automatically set the value for this two attributes when an object is created and every time it is updated.

2) Field order

If you want Grails to generate the fields for the create, edit & show views in a particular order, just define that order on the constraints. If the attribute doesn’t require a specific constraint (such as maxSize, unique, nullable, etc), just put the attribute on the constraints and leave the constraint empty.


static constraints = {
name()
address()
city(nullable:true, blank:true)
phone(nullable:true, blank:true)
mobile(nullable:true, blank:true)
email(email:true)
}


3) Unique by group

If you want an attribute on a domain class to be unique, but only grouped by another attribute, you can do it. In the following example, the company name will be unique only for companies from the same client:


class Company {

Client client
String name
String address

static constraints = {
name(size:3..50, blank:false, unique:'client')
address()
}
}


4) Change database mapping for String attribute

Grails will map the String attributes on your domain class to varchar(255) by default. If you want a String attribute mapped to text, here’s how you do it:


static mapping = {
columns{
attribute_name type:"text"
}
}


Stay tuned for more Grails tips!