Thursday, November 09, 2006

Grails 0.3: Hibernate mapping has never been this easy

We've just put out Grails 0.3, which is a marked improvement over 0.2.2. Checkout this post for more info.

Possibly my favourite new feature of 0.3 is the improvements made to GORM, the ORM side of things that is built on Hibernate. It has become really concise. Defining persistent entities with relationships is as simple as:


class Author {
static hasMany = [ books : Book ]

String name
}
class Book {
static belongsTo = Author

Author author
String title
}


Here we have a bidirectional one-to-many relationship. The 'hasMany' setting will inject a 'books' java.util.Set property into the class at compile time. Also injected are an 'id' property, and Hibernate's 'version' property to aid in transactions and optimistic locking.

GORM configures these classes as regular Hibernate persistent classes, but with a twist because Grails injects all sorts of helpful methods into them at runtime too. Such as those to manage relationships:


def a = new Author(name:"Stephen King")
.addBook(new Book(title:"IT"))
.addBook(new Book(title:"The Stand"))
.save()


Here you create a new author instance, add two books to it and save it. In the background Grails is managing the relationships for you, making sure that both the one and the many side have references to each other and then through Hibernate persisting the instance with updates cascading to from the Author to each Book.

Notice how unobtrusive GORM is? No XML, no annotations clouding your domain model, just pure application logic that defines the relationships. And yet at the same time underneath it all it is still Hibernate, making it robust and enterprise ready.

This is of course only a small example, there are many more features of GORM such as all those dynamic finder and persistence methods. We have a lot more planned for 0.4, the next month is going to be fun. :-)

3 comments:

Anonymous said...

Congratulations to the Grails team!. Quick question: will your upcoming book on Grails include some of the features of this new release ?

Graeme Rocher said...

Hi Andres,

Yes the book covers 0.3

Cheers!

Anonymous said...

Do they have mailing lists on grails as they have on rails?
I am running XP Pro.
I can't get the environment variables to access grails from the command line unless I first go the bin folder and then type "grails"
I set GRAILS_HOME = c:\groovy\grails_0.3.1
I then set PATH =%GRAILS_HOME%\bin


I have closed down my computer, bing it back up, and I still can't get it to execute "Grails"
Any help will be appreciated. I am already running RAILS ok.
Jim