Grails Cookbook - A collection of tutorials and examples

Grails Tutorial for Beginners - Introduction to GORM

GORM is half the reason why I use Grails as my default choice in implementing new projects. Using it just makes implementation of business logic a breeze. Working with a database becomes so easy.
GORM is Grails' object relational mapping (ORM) implementation, which sits on top of the very popular Hibernate framework. If you are familiar with Hibernate, then you can pick up GORM in an instant. Don't worry otherwise as GORM is straightforward and easy to learn.

Object-relational mapping (ORM)

Relational database is still the most popular way to store and retrieve information because the technology is very mature and it has many software options. Oracle and MS SQL Server are popular for commercial products, while MySQL and PostgreSQL are strong Open Source alternatives.
Working with relational database directly in Grails/Java is tricky. Because you think in terms of tables in database, while you think in terms of Classes and objects in Java. Wouldn't it be easier and more efficient if we just think in terms of objects and forget about tables?

For example, here is a code snippet on how we save a record in the database using plain JDBC:

public void save(Person person) {
    try{
        Connection conn = Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "root");
        Statement stmt = conn.createStatement();
        String sql = "INSERT INTO person (first_name, last_name) VALUES ('"+p.getFirstName()+"', '"+p.getLastName()+"')";
        stmt.executeUpdate(sql);
    }catch(Exception e){
	    ...
    } finally{
	    ...
    }
}

Wouldn't it be cool if we could save information to the database by having this instead?

new Person(firstName:'John', lastName:'Doe').save()

ORM frameworks objective is to present an API where you can just think and program in objects, and the underlying framework will handle how to interface with the relational database.

Configuration

Since Grails is a framework that don't want to get in the way, it has a default database configuration already so that you could start coding your business logic right away. By default, it uses an embedded H2 database. But if you wish to modify this, the config file to edit is DataSource.groovy.

Domain Object

Create a groovy class inside the domain folder (E.g. PROJECT_DIR\grails-app\domain). For example, Person.groovy

package testing
class Person {
    String firstName
    String lastName
    Date dateOfBirth
    double salary
}

You can then start up your application and the corresponding table will be created automatically for all your domain classes. You don't have to create the tables manually in your database or write an sql statement for this. For this example, table person will be created with columns first_name, last_name, date_of_birth, and salary. The correct sql data type will be applied ( E.g. varchar for String).
The generated table in MySQL is below:
table_person
Notice that Grails automatically add 2 columns id and version. Column id will be the primary key for the table. Column version is used to version the updates to the row. This is usually important for optimistic locking.

Create, Read, Update, Delete (CRUD)

When you have prepared your domain class, you can then immediately write code to create, read, update, or delete records to the database already without writing any plumbing code. Usually, you will write GORM code insite Bootstrap, controllers, and services.
Create Record
To insert a row to the person table, your code will look like this:
Person p = new Person()
p.firstName = 'John'
p.lastName = 'Doe'
p.save()
Alternate shortcut code is below:
Person p = new Person(firstName:'John', lastName:'Doe').save()
Notice that the domain instance itself knows how to persist itself. In usual Java frameworks, our Pojo and DAO code are separate. But in GORM, it seems they are merged together.

Read
In case you know the primary key (id) of a specific row (e.g. id = 999), you can retrieve it like this:

Person p = Person.get(999)

Update
Updating an existing is as simple as calling the save method of the domain instance. For example, to increase the salary of a person:

Person p = Person.get(999)
p.salary = p.salary + 1000
p.save()

Delete
To delete, just invoke the delete method on the domain instance:

Person p = Person.get(999)
p.delete()

Other goodies

Aside from the methods available above, there are other many useful methods. Some are dynamically available. Just to give a quick overview, you can do these thigs:

Number of records in person table:

int numberOfRecords = Person.count()

Number of records with last_name = Doe:

int numberOfRecords = Person.countByLastName("Doe")

Find 1 record with first_name = John, and last_name = Doe:

Person p = Person.findByFirstNameAndLastName("John", "Doe")

Find all records with last name = Doe:

def list = Person.findAllByLastName("Doe")

Remarks

As shown above, GORM really makes writing of business logic very easy and convenient since you don't have to write any plumbing code. Another advantage not mentioned above is that Grails applications are database agnostic. Since GORM provides an abstraction layer from the database (i.e. you don't write code specific to a certain database product), your application can be deployed to any major database systems without changing any code. You can write once and deploy to an environment with MySQL, Postgres, Oracle, and others.

List of Tutorials for Beginners

Tags: beginner, crud, database, gorm, orm, tutorial