Last updated by engrean 6 years ago

Quick Start

The following makes it simple to start a grails project. There is also a series of screencasts that will take you from the basics to a full working Grails application.

There is a Portuguese Version on this Quick Start guide.

Create a Grails project

Once you have installed Grails you can use the built-in target for creating new projects:

grails create-app my-project
This creates a new directory named after your application and containing the project structure below:
    + grails-app
       + conf                 ---> location of configuration artifacts 
           + hibernate        ---> optional hibernate config
           + spring           ---> optional spring config
       + controllers          ---> location of controller artifacts
       + domain               ---> location of domain classes
       + i18n                 ---> location of message bundles for i18n
       + services             ---> location of services
       + taglib               ---> location of tag libraries
       + util                 ---> location of special utility classes 
       + views                ---> location of views
           + layouts          ---> location of layouts
   + lib
   + scripts                  ---> scripts
   + src
       + groovy               ---> optional; location for Groovy source files
                                   (of types other than those in grails-app/*)
       + java                 ---> optional; location for Java source files
   + test                     ---> generated test classes
   + web-app
       + WEB-INF

Create a Domain Class

The core of most Grails applications is the domain model, which represents the persistent data of the application. Creating some persistent data is as simple as creating a new domain class:

cd my-project

grails create-domain-class org.example.Book

This command will create the file Book.groovy in the grails-app/domain/org/example directory. This is a straight text file that you can edit with your favorite text editor or IDE.

Note: The names of database tables are automatically inferred from the name of the domain class. This can cause problems if the table name matches a keyword in your database. For example, the domain class Group becomes the table 'group' by default, but this is a keyword in MySQL. In such cases, try a different name such as UserGroup or look at the section titled Custom ORM Mapping in the user guide.

All explicitly typed properties are by default persisted to the database, so let's add some to our Book class now:

package org.example

class Book { String title String author

static constraints = { title(blank: false) author(blank: false) } }

The result of the above code is that when we save an instance of Book , its title and author are persisted to the database. Note that we haven't configured the database nor have we created the tables and columns: this all happens automatically.

So what's the constraints property about? That allows you to specify validation requirements for the properties of your domain class. In this particular case, we're declaring that neither title nor author can be blank, i.e. an empty string or a string that only contains whitespace (spaces, tabs, etc.). There are quite a few built-in constraints and you can even add your own - check out the user guide for more information on validation. You can for example specify that a property must be an email address or have a particular length.

Create a controller

Controllers are central to generating your user interface or providing a programmatic REST interface. They typically handle the web requests that come from a browser or some other client and you'll find that each URL of your application is usually handled by one controller.

Grails provides a feature called scaffolding that automatically creates a user interface for a domain class that allows you create new instances, modify them, and delete them. Enabling scaffolding is very straightforward. We start by creating a controller for our domain class:

grails create-controller org.example.Book // Note the capital B

Note how we specify the full class name of the domain class, including the package. This commands creates us the file grails-app/controllers/org/example/BookController.groovy that contains our controller code. Notice how it is named after the domain class but with a 'Controller' suffix? The suffix is important as it identifies the class as a controller.

So now that we have the controller class, open it up and modify it to make the content look like

package org.example

class BookController { def scaffold = Book // Note the capital "B" }

This will mean removing the def index = { } line, but that's fine. You're now ready to test out your first Grails application!

Start Grails

To start your Grails application run the following command:

grails run-app

This will start up a servlet container (Tomcat). Once the command says the container has started and prints out the URL, copy the link to a browser and view the page. It should display a welcome message and a link to org.example.BookController - click that link to display the scaffolded pages for Book . You'll be able to create new books, modify existing ones, and delete them.

Congratulations, you have written your first Grails application!

What's Next

So, you've written your first Grails application. What should your next steps be? Let's start by looking at some enhancements you can make to the application.

Creating test data

Wouldn't it be great if every time you started the server you saw a list of books already displayed in the scaffolded pages? This is easy to achieve by creating the underlying Book instances in the Grails BootStrap class, which you can find in grails-app/conf/BootStrap.groovy :

import org.example.Book

class BootStrap { def init = { servletContext -> // Check whether the test data already exists. if (!Book.count()) { new Book(author: "Stephen King", title: "The Shining").save(failOnError: true) new Book(author: "James Patterson", title: "Along Came a Spider").save(failOnError: true) } }

def destroy = { } }

You see, this init block is executed every time your application starts, whether via grails run-app or when its deployed to a servlet container as a WAR file. The destroy block is likewise executed when the application is terminated.

The first thing to note is the call to Book.count() . This method returns the number of Book instances currently in the database, so we can use it to check whether the test data is already there. If there's no data the method returns 0, which Groovy treats as equivalent to the boolean false in the condition.

So, once we've determined that the test data doesn't exist, we create new Book instances using what Groovy calls 'named arguments' to set the properties. The save() method then persists the Book instances to the database.

The failOnError option ensures that an exception is thrown if the save fails for any reason, for example if the domain class's constraints are violated. By default, save() returns null if the save fails. An exception is particularly useful in BootStrap because you typically expect the save to succeed and any failure is down to programmer error.

You can put any code you like in BootStrap . You can even do different things based on the current environment. To find out more, check out the user guide.

If you want your data to last beyond the server shutting down, you will need to configure an alternative database.

Configure a Data Source (Optional)

All new Grails applications include the file grails-app/conf/DataSource.groovy which contains details of the database the application uses. This allows you to set both common settings and per-environment ones.

By default, an application is configured to use an in-memory HSQLDB database for development and testing. If you wanted to use MySQL in production for example, you would have to configure it here:

dataSource {
// environment specific settings
environments {
    development {
        dataSource {
    test {
        dataSource {
    production {
        dataSource {
            dbCreate = "update"
            driverClassName = "com.mysql.jdbc.Driver"
            url = "jdbc:mysql://localhost/my_app"
            username = "root"
            password = ""

Most of these settings are self-explanatory if you're familiar with JDBC (you can easily find the appropriate settings for your database by doing a web search for "JDBC" + the name of your database provider, e.g. PostgreSQL), but dbCreate deserves a special mention. It determines what happens to your database between server restarts. For example, a value of create-drop means that the database tables will be dropped and then recreated when you start the server, so you lose any data that was in there. This is fine for testing, but is definitely not what you want in production. The user guide has more information on these settings.

See this post on how to connect to an HSQL Database using DBVisualizer (this is useful to see the schema grails automatically generates).

If you want to run your application against a database provider other than HSQLDB, then changing your settings in DataSource.groovy isn't enough. You must also add the JDBC driver, which is typically provided in a JAR. Now, you can drop this the driver JAR into your application's lib directory, but from Grails 1.2 onwards it's much better to declare it as a dependency in grails-app/conf/BuildConfig.groovy - as shown in this example:

grails.project.dependency.resolution = {
    inherits "global"
    log "warn"

repositories { grailsHome() grailsPlugins() grailsCentral()

mavenCentral() }

dependencies { … runtime "postgresql:postgresql:8.3-603.jdbc3" } }

Make sure to specify the JDBC driver as a runtime dependency and you will almost certainly want to add mavenCentral() to your repositories as well so Grails can find it.

And then