Wednesday, July 08, 2009

Grails cheatsheet

Getting Started
grails set-proxy (if necessary to set proxy)
grails create-app AppName
cd AppName
grails create-domain-class Domain
grails generate-all Domain

Install Acegi
grails install-plugin acegi
grails create-auth-domains
grails generate-manager
grails generate-registration

grails schema-export (Export a DDL sql script for the domain classes)
grails generate-hbm-xml (Generate hibernate mapping file (From grails 1.3)
grails install-templates (Install base scaffolding files. Can then update them before generating scaffolding.
e.g. I update list default size to 50 (from 10)), Increase number of columns displayed in list tables (max by defauilt is 6 columns), changing if (i < 6){ { allows you to increase this (change in 2 places)

grails install-plugin db-stuff
grails create-db
grails export-data
grails export-data-diff
grails export-ddl
grails load-data

Maven integration
Build a new grails project with maven.
mvn org.apache.maven.plugins:maven-archetype-plugin:2.0-alpha-4:generate -DarchetypeGroupId=org.grails -DarchetypeArtifactId=grails-maven-archetype -DarchetypeVersion=1.2.0 -DgroupId=example -DartifactId=my-app

mvn initialize

  1. GORM Non numeric ID field
See my question, and someone elses helpful answer on the grails mailing list for how to create a non-numeric ID field, and rename it to something other than ID. Its a bit sneaky but works perfectly.
  1. Dependency Injection.
Ran into a stupid problem with Dependency injection. I was trying to inject the DataSource into a Service (and into a Java library). It appeared the Data source was not getting injected into grails Service class. Dependency injection was not working!!
As usual it was working fine, and the problem was mine...
Dependency Injection (DI) is configured by default to occur by name. If you create a property in your Domain/ Controller/ Service class with the same name as another Service or property you want injected, then it will automatically get injected. See this article
To inject the DataSource into your Service, All you need to do is add the line
def dataSource
to your Service. Thats all.. nothing else is needed.

I also had to add the following to initialize the java libraries dataSource, so I also needed
class BenefitService implements InitializingBean{
void afterPropertiesSet() {
println "Initializing BenefitService "+dataSource
This all would work. My problem was I (helpfully) added an accessor method for the dataSource
def getDataSource(){return dataSource)
This simple method modifies the groovy class dataSource property, effectively making the setter of the dataSource unavailable, thus effectively blocking dependency injection.
Moral: Groovy is designed to help reduce the number of code lines you write. Don't add unneccessary lines or there may be unexpected side-effects.