Grails Cookbook - A collection of tutorials and examples

Grails Tutorial for Beginners - Display Data from the Database

The most common thing we want to do in Grails is to read data from the database and display it to the user. This post is a simple walk-through on how to accomplish this.

Create a Domain Class

We first need to create a domain class. For example:
package asia.grails.myapp
class Person {
    String firstName
    String lastName
    int age
}
You need to save this under grails-app/domain folder. It is advisable to create a package structure under this folder.
When you start your application, Grails will automatically create a database table for each domain class you have. In our example, the table "person" will be created with columns "first_name", "last_name", and "age".

If you are new to Grails and domain classes, read my previous post about gorm.

Insert Some Data using Bootstrap.groovy

For convenience, there is a class in Grails called Bootstrap.groovy. It is under grails-app/conf folder. When your application starts, Grails will execute the code inside it. You can use this to automatically populate your tables with test data. For example:
import asia.grails.myapp.Person
class BootStrap {
    def init = { servletContext ->
        if (Person.count() == 0) {
            new Person(firstName: 'John', lastName: 'Doe', age: 20).save()
            new Person(firstName: 'Jane', lastName: 'Smith', age: 18).save()
            new Person(firstName: 'Scott', lastName: 'Robinson', age: 42).save()
        }
    }
    def destroy = {
    }
}
What the code does is on startup, it will check the number of rows in the person table. If none exists, 3 person records will be inserted.

Controller Code

You can create a simple controller, read data from the database and pass it to your GSP.
package asia.grails.myapp
class PersonController {
    def index() {
        def persons = Person.list()
        [persons:persons]
    }
}
The code def persons = Person.list() will fetch all records in person table and store it in persons variable. In Groovy, the last statement you have in a method, is the value that will be returned to the caller. In the example above, the index() method will return a map of values. It contains a single object with name "persons", and the value is the list of items read from the database. This map will be passed to your view (GSP).
If you are unfamiliar with controllers, read this post about MVC and this post about controllers.

View Code

The map of objects passed from the controller will be available inside your view. For example:
<!DOCTYPE html>
<html>
	<head>
		<meta name="layout" content="main"/>
		<title>Persons</title>
	</head>
	<body>
        <g:each in="${persons}" var="person" status="i">
            <h3>${i+1}. ${person.lastName}, ${person.firstName}</h3>
            <p>
                Age: ${person.age}
            </p>
            <br/>
        </g:each>
	</body>
</html>
As shown above, the persons variable can be used right away.

Remarks

Our simple example above will have the following output:
zzxx01

List of Tutorials for Beginners

Tags: beginner, gorm, gsp