Summary
Grails is a relatively new Web application framework based on Groovy. In a recent IBM developerWorks article, Scott Davis explains GORM, Grails' object-relational mapping tool.
Advertisement
Many Web application frameworks provide some form of object-relational mapping as part of their persistence layer. Grails is no exception: It provides GORM, a tool that maps Groovy objects to relational database tables. In a recent IBM developerWorks article, GORM: Funny name, serious technology, Scott Davis introduces this technology:
GORM is a thin Groovy facade over Hibernate... This means that all your existing Hibernate tricks still work—for example, HBM mapping files and annotations are both fully supported...
GORM [allows] you to represent your object model in a way that makes sense in Groovy. It handles the relational database issues for you behind the scenes, but ... you can easily override the default settings. Rather than being an opaque abstraction layer that hides the database details from you, GORM is a translucent layer—it tries to do the right thing out of the box, but it doesn't get in your way if you need to customize its behavior. This gives you the best of both worlds.
Davis highlights many features of GORM that will look familiar to Rails developers, such as the way Groovy classes are used to define many-to-one relationships, as in this example:
class Airline {
static hasMany = [trip:Trip]
String name
String url
String frequentFlyer
String notes
}
The static hasMany setting is a Groovy hashmap: the key is trip; the value is the Trip class. If you want to set up additional one-to-many relationships with the Airline class, you can put a comma-delimited list of key/value pairs inside the square brackets...
This naked objects pattern of decorating the domain object ... is used extensively throughout Grails. By adding this information directly to the POGO, you eliminate the need for external XML configuration files. Having all the information in a single place is a great boon to productivity.
Davis illustrates many other ways objects can be used to configure the object-relational mapping tool, and even elements of the Web tier, such as adding the order in which fields are displayed, as well as validations:
The static constraints block also lets you put some validation rules in place. For example, you can enforce length restrictions on String fields. (They default to 255 characters.) You can ensure that String values match a certain pattern (such as an e-mail address or URL). You can even make fields optional or required: