The Grails Object Relational Mapping (GORM)

Exclusive offer: get 50% off this eBook here
Groovy for Domain-Specific Languages

Groovy for Domain-Specific Languages — Save 50%

Extend and enhance your Java applications with Domain Specific Languages in Groovy

$26.99    $13.50
by Fergal Dearle | June 2010 | Java Open Source

The Grails Object Relational Mapping (GORM) is a core component of the Grails web application framework and uses DSL- style techniques to apply persistence to regular Groovy classes.

In this article by Fergal Dearle, author of the book Groovy for Domain-Specific Languages, we will take a look at the Grails Object Relational Mapping (GORM). We will also see how a GORM model is built.

(For more resources on Groovy DSL, see here.)

The Grails framework is an open source web application framework built for the Groovy language. Grails not only leverages Hibernate under the covers as its persistence layer, but also implements its own Object Relational Mapping layer for Groovy, known as GORM. With GORM, we can take a POGO class and decorate it with DSL-like settings in order to control how it is persisted.

Grails programmers use GORM classes as a mini language for describing the persistent objects in their application. In this section, we will do a whistle-stop tour of the features of Grails. This won't be a tutorial on building Grails applications, as the subject is too big to be covered here. Our main focus will be on how GORM implements its Object model in the domain classes.

Grails quick start

Before we proceed, we need to install Grails and get a basic app installation up and running. The Grails' download and installation instructions can be found at http://www.grails.org/Installation. Once it has been installed, and with the Grails binaries in your path, navigate to a workspace directory and issue the following command:

grails create-app GroovyDSL

This builds a Grails application tree called GroovyDSL under your current workspace directory. If we now navigate to this directory, we can launch the Grails app. By default, the app will display a welcome page at http://localhost:8080/GroovyDSL/.

cd GroovyDSL
grails run-app

The grails-app directory

The GroovyDSL application that we built earlier has a grails-app subdirectory, which is where the application source files for our application will reside. We only need to concern ourselves with the grails-app/domain directory for this discussion, but it's worth understanding a little about some of the other important directories.

  • grails-app/conf: This is where the Grails configuration files reside.
  • grails-app/controllers: Grails uses a Model View Controller (MVC) architecture. The controller directory will contain the Groovy controller code for our UIs.
  • grails-app/domain: This is where Grails stores the GORM model classes of the application.
  • grails-app/view: This is where the Groovy Server Pages (GSPs), the Grails equivalent to JSPs are stored.

Grails has a number of shortcut commands that allow us to quickly build out the objects for our model. As we progress through this section, we will take a look back at these directories to see what files have been generated in these directories for us.

In this section, we will be taking a whistle-stop tour through GORM. You might like to dig deeper into both GORM and Grails yourself. You can find further online documentation for GORM at http://www.grails.org/GORM.

DataSource configuration

Out of the box, Grails is configured to use an embedded HSQL in-memory database. This is useful as a means of getting up and running quickly, and all of the example code will work perfectly well with the default configuration. Having an in-memory database is helpful for testing because we always start with a clean slate. However, for the purpose of this section, it's also useful for us to have a proper database instance to peek into, in order to see how GORM maps Groovy objects into tables. We will configure our Grails application to persist in a MySQL database instance.

Grails allows us to have separate configuration environments for development, testing, and production. We will configure our development environment to point to a MySQL instance, but we can leave the production and testing environments as they are.

First of all we need to create a database, by using the mysqladmin command. This command will create a database called groovydsl, which is owned by the MySQL root user.

mysqladmin -u root create groovydsl

Database configuration in Grails is done by editing the DataSource.groovy source file in grails-app/conf. We are interested in the environments section of this file.

environments {
development {
dataSource {
dbCreate = "create-drop"
url = "jdbc:mysql://localhost/groovydsl"
driverClassName = "com.mysql.jdbc.Driver"
username = "root"
password = ""
}
}
test {
dataSource {
dbCreate = "create-drop"
url = "jdbc:hsqldb:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:hsqldb:mem:testDb"
}
}
}

The first interesting thing to note is that this is a mini Groovy DSL for describing data sources. In the previous version, we have edited the development dataSource entry to point to the MySQL groovydsl database that we created.

In early versions of Grails, there were three separate DataSource files that need to be configured for each environment, for example, DevelopmentDataSource.groovy. The equivalent DevelopmentDataSource.groovy file would be as follows:

class DevelopmentDataSource {
boolean pooling = true
String dbCreate = "create-drop"
String url = " jdbc:mysql://localhost/groovydsl "
String driverClassName = "com.mysql.jdbc.Driver"
String username = "root"
String password = ""
}

The dbCreate field tells GORM what it should do with tables in the database, on startup. Setting this to create-drop will tell GORM to drop a table if it exists already, and create a new table, each time it runs. This will keep the database tables in sync with our GORM objects. You can also set dbCreate to update or create.

DataSource.groovy is a handy little DSL for configuring the GORM database connections. Grails uses a utility class—groovu.utl. ConfigSlurper—for this DSL. The ConfigSlurper class allows us to easily parse a structured configuration file and convert it into a java.util.Properties object if we wish. Alternatively, we can navigate the ConfigObject returned by using dot notation. We can use the ConfigSlurper to open and navigate DataSource.groovy as shown in the next code snippet. ConfigSlurper has a built-in ability to partition the configuration by environment. If we construct the ConfigSlurper for a particular environment, it will only load the settings appropriate to that environment.

def development =
new ConfigSlurper("development").parse(new
File('DataSource.groovy').toURL())
def production =
new ConfigSlurper("production").parse(new
File('DataSource.groovy').toURL())
assert development.dataSource.dbCreate == "create-drop"
assert production.dataSource.dbCreate == "update"
def props = development.toProperties()
assert props["dataSource.dbCreate"] == "create-drop"

Groovy for Domain-Specific Languages Extend and enhance your Java applications with Domain Specific Languages in Groovy
Published: June 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

(For more resources on Groovy DSL, see here.)

Building a GORM model

The grails command can be used as a shortcut to carve out GORM domain classes. We can create a domain class for Customer by issuing the following Grails command from the GroovyDSL application directory:

grails create-domain-class Customer

This will create a stub Customer.groovy file in the grails-app/domain directory, as follows:

class Customer {

    static constraints = {
    }
}

If we add some fields to this class, we can peek into the MySQL database to see how GORM automatically creates a table for this class.

class Customer {
   String firstName
   String lastName

    static constraints = {
    }
}

Now if we restart Grails by issuing the grails run-app command, we can inspect the resulting table in MySQL:

GORM has automatically created a customer table for us in the groovydsl database. The table has two fields by default, for the row id and the object version. The two fields we added to Customer have been mapped to the first_name and last_name of Type varchar(255) columns in the database.

Using domain classes

Now that we have a domain class, how do we go about trying it out? We could dive in and write controllers and a view in order to build UI pages for the Customer object, which would be the norm if we were building a full-blown Grails application. We don't want to do this as all we want to do is look at how the GORM model is constructed.

Fortunately, Grails has some ways to let us interact directly with model classes without building any UI superstructure. The simplest of these is to use the GroovyConsole. The grails command can be used to launch the console with the Grails environment running, so that model classes are immediately accessible.

$g rails console

A normal POGO class would only allow us to construct it and interact with its properties at this point. However, Grails has used the Groovy MOP to add some persistence methods to the Customer class. If we run the code shown in the previous example, we call the save method on a Customer object that causes it to be stored in the MySQL database. Using mysql we can confirm to our satisfaction that a row has actually been saved, by doing this:

mysql> select * from customer;
+----+---------+------------+------------+
| id | version | first_name | last_name |
+----+---------+------------+------------+
| 1  |       0 | Fred       | Flintstone |
+----+---------+------------+------------+
1 row in set (0.00 sec)


mysql>

We also have methods to get( ) an object from the database by ID, update() the object, and list() available objects.

def barney = new Customer(firstName: "Barney", lastName: "Rubble")
barney.save()

def fred = Customer.get(1)
fred.firstName = "Fred"
fred.save()

def customers = Customer.list()
customers.each { println c.id + ": " + c.firstName + " , " +
c.lastName }

The above example saves a new customer "Barney" to the database, gets the customer object for "Fred", and updates the firstName field. The list method returns all customers as a regular list collection so that we can apply a closure to all members to print them.

1: Fred, Flintstone
2: Barney, Rubble

Let's take a second to look at what Grails has done to our class. The Customer class that we declared had no base class to inherit methods from, and it did not define these methods. Grails has used the Groovy MOP to add these methods. When we run our Grails app in development mode, Grails iterates of all the domain classes in grails-app/domain. As it does so, it adds these persistence methods to the MetaClass of each doma in class that it encounters. We have covered several different options as to how to add a method to a class on the fly. In this case, Grails has augmented the MetaClass for Customer with a combination of static and normal methods, as follows:

class Customer {
 ...
}
Customer.metaClass.static.get = { ... }
Customer.metaClass.static.list = { ... }
Customer.metaClass.save = { ... }

Summary

This article gave us an overview of the Grails Object Relational Mapping (GORM). We also saw the building of a GORM model using domain classes.


Further resources on this subject:


Groovy for Domain-Specific Languages Extend and enhance your Java applications with Domain Specific Languages in Groovy
Published: June 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Fergal Dearle

Fergal is a seasoned software development professional with 23 years of experience in software product development across a wide variety of technologies. He is currently principal consultant with his own software development consulting company, Dearle Technologies Ltd., engaged in design, development, and architecture for new software products for client companies. In the past Fergal has worked in lead architect and developer roles for Candle Corporation on the OMEGAMON product which is now part of IBMs Tivoli product suite as development manager for the Unix implementations of Lotus 1-2-3. In the early 1990s Fergal lead the team at Glockenspiel that developed CommonView, the first object-oriented UI framework for Microsoft Windows. The team was awarded one of the first ever Jolt Productivity Awards by Dr Dobbs Journal.

Books From Packt


Spring Security 3
Spring Security 3

NHibernate 2 Beginner's Guide
NHibernate 2 Beginner's Guide

Plone 3 Multimedia
Plone 3 Multimedia

Liferay Portal 6   Enterprise Intranets
Liferay Portal 6 Enterprise Intranets

Oracle JRockit: The Definitive Guide
Oracle JRockit: The Definitive Guide

Amazon SimpleDB Developer Guide
Amazon SimpleDB Developer Guide

JSF 2.0 Cookbook
JSF 2.0 Cookbook

NetBeans Platform 6.9 Developer's Guide
NetBeans Platform 6.9 Developer's Guide

Your rating: None Average: 4.5 (2 votes)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
x
y
p
W
Z
4
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software