Grails for the Wicked Smaht

Grails for the Wicked Smaht

Something I like about Groovy/Grails is that I seem to get 90% of my work done with 10% of the language/framework. Here’s a guide to the 10%, intended for folks who already know what they’re doing with Web technologies.

Pretty much every entry in here has multiple pages (or even chapters) of documentation on the Groovy or Grails homepage, and is probably covered in-depth in a book. This is not that documentation or book.

Some things may seem restrictive, like “a controller method assumes a like-named view.” That’s just a convention, and I haven’t hit a Grails convention yet that won’t allow you to override it, whether it’s view names or complicated model-to-database table mappings.

Groovy

Language

It compiles to .class, so you can use it from Java or use anything Java from Groovy.

Everything’s an Object

Declare an int, you get an Integer. This means boxing. Drop to Java for fast math.

Strings

Strings in single quotes are literals. String in double quotes are “GStrings” (chuckle), and lazily evaluate anything inside of ${}.

(Hash)Maps and (Array)Lists are simple, replacing Arrays and such.

Declare them a lot like JSON, but with square brackets.

Closures may be new to you.

They’re anonymous function that can be assigned to variables, passed, etc. They have access to the scope around them.

Loop with Closures

“For” and such exist, but closures own loops. Each, EachWithIndex, Collect…there’s a lot of things you can do with them.

Truthiness

Null is false. Empty collections are false. Empty strings are false. Empty iterators/vectors or those at their end are false. Common sense, really.

Classes and Beans

Getters/Setters are Implied

Here’s a Person bean. Java code would see getFirstname() and such.

Constructors take maps

Access via properties or dynamically.

All valid:

You can write your own getter/setter to override.

Grails

Grails is MVC with Spring and Hibernate (or MongoDB or whatnot) already hooked up and simplified. You can pretty much do anything possible in raw Java+Spring+Hibernate, but Grails simplifies the way 95% of folks did 95% of their tasks.

Installing

Download Grails and set a GRAILS_HOME environment variable to the unzipped directory. Add GRAILS_HOME/bin to your path. Done.

Creating an application

Navigate to the desired parent directory and do “grails create-application MyApplication”.

Application directory structure

It’s pretty straightforward. Directories are named what they contain. Grails-app contains your application, and grails-app/controller contains controllers. This pattern persists throughout.

Running your application

Go to your application’s directory and type “grails”. This’ll start the “interactive shell.” Now, type run-app and it’ll run and tell you the URL, like http://localhost:8080/MyApplication.

Model

Saveable Domain Models

The “Person” we already wrote is all we need. Grails will infer an autoincrementing “id” property and optimistic locking in a “version” property, adding them on the fly.

Data access, finders, and such

Anything that’s a Grails domain model can save, read, list, and generally CRUD. You can use dynamically-created methods, HQL, or criteria.

Relating Entities

Many-To-One

Add a property and say the child “belongsTo” the parent to enable cascading.

One-To-Many

Add a static “hasMany” and declare a property if you want a collection type other than Set:

Add to “one to manys” on the “parent” side with generated methods

Validation

Add constraints to a model and it’ll runtime validate (using Spring validation) and manage database constraints for you. You can write custom validations. “nullable: false” is implied for EVERYTHING, and must be set to true to override.

Controller

A Grails controller defines methods that equate to URLs.

Controller Methods

This’ll define /person/show, allowing /person/show?personId=2. URL/form values go into a ‘params’ map. A map returned by the method contains values available in the view.

Views

A method assumes a like-named view. If one doesn’t exist, and you don’t explicitly do a render() or redirect() in your controller’s method, you get a 404. Therefore, here’s /view/person/show.gsp:

Grails tags

Grails defines a bunch of tags, like,and so on. I’d read up on what’s available and make use them.

JSON/Ajax/XML

Use “as JSON” or “as XML” to render something in place of a .gsp view:

This works on lists, maps, whatever.

Services

Your controllers shouldn’t really do anything except marshal form/URL input onto models and control application flow (where a user goes and when). Heavy lifting should be deferred to services. Every method in a service is wrapped in a transaction. This can be turned off.

Going Further

I’ve described the 2% of Groovy and Grails I use constantly, and ignored 98% of what they can do. I’ve done full-bore integration of x509 authenticated JEE applications using JPA annotations into Grails, Spring-Security work, Web Services, all that jazz. All of JEE is there, and it can all be configured however you need. HTML5 and JavaScript frameworks are easy to integrate. A huge library of community-driven plugins exists to take care of common stuff, like e-mail integration or security.

Groovy and Grails just reduce the amount of BS involved, letting you focus on what’s actually important to your application and its users rather than 5,000 XML files that contain tweaked boilerplate pasted from documentation.

Joe Rinehart's been developing software for Web, mobile, and desktop since 1998. While he mainly now works in Java, Grails, and HTML5, he has a long history of community involvement in the Flash, Flex, and ColdFusion space. As a published author and award-winning speaker, he's bringing his skills to CompileDammit to help users new to Grails and Java. When he's not coding, he's either spending time with his family or feeding an appetite for endurance mountain bike racing. (8/9/2012 update: He's now either spending time with his family or getting over a huge knee injury caused by endurance mountain bike racing.)

Posted in Uncategorized
4 comments on “Grails for the Wicked Smaht
  1. wwwclaes says:

    Thanks for the nice intro to Grails. GitHub seems to think you are too popular or something, many code samples are currently replaced with this:

    Could not embed GitHub Gist 3911192: API Rate Limit Exceeded for 178.63.146.0

    I hope the knee injury is all gone and that you are back on the bike!

  2. dmahapatro says:

    It’s “grails create-app MyApplication” instead of “create-application”. I think that was just a typo. A very well tailored blog to get a gist on Groovy and mainly on Grails.

  3. bchesley says:

    Excellent summary. Kinda like ‘Groovy/Grails: The Good Parts’ and I am sure I will be revisiting this frequently.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>