Grails 4 Tutorial: Easy to Build CRUD Web Application

by Didin J. on Dec 09, 2019 Grails 4 Tutorial: Easy to Build CRUD Web Application

How easy to build a simple create-read-update-delete (CRUD) web application using Grails 4 framework

In this Grails 4 tutorial, we will show you how easy to build a simple create-read-update-delete (CRUD) web application using Grails 4 framework. A few years ago we have shown you a similar tutorial for Grails 3. There are no significant changes in the Grails framework or Groovy usage between Grails 3 and Grails 4. But there are a lot of performance improvements, features, compatibility with the new technology, etc.

Table of Contents:

As you see in the table of contents, there are just a few steps to build a Grails 4 CRUD web application easily. We will use HSQLDB or H2 in-memory databases as datastore. So, there is not much configuration or required tools or libraries. The following tools, frameworks, and libraries are required for this tutorial:

  1. JDK 8
  2. Grails 4
  3. Terminal (Mac OS/Linux) or Command Line (Windows)
  4. IDE or Text Editor (We are using Visual Studio Code)

You can watch the video tutorial from our YouTube channel.

Let's get started with the main steps!


Step #1. Preparation

The principal of building Grails 4 application is installing Grails 4 and Groovy SDK which required JDK 8 installed on your machine. First, download and install the Java Development Kit (JDK) from the official Oracle download page. Next, make sure the JDK 8 is added to your environment variables or path. If JDK 8 already installed and added to the path, check it by open the terminal or command line then type this command.

java -version
java version "1.8.0_92"
Java(TM) SE Runtime Environment (build 1.8.0_92-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.92-b14, mixed mode)

Next, install the Grails 4 and Groovy SDK by downloading it from the official Grails download page. Extract or install it to your machine then add to the environment variables path. On Mac OS, we are using SDKMan to install it by simply run this command in the terminal.

sdk install grails

To check the installed Grails SDK, type this command.

grails -version
| Grails Version: 4.0.1
| JVM Version: 1.8.0_92

Now, Grails 4 is ready to create a new application.


Step #2. Create and Configure a Grails 4 Web Application

We will use Grails 4 CLI to create a new Grails 4 web application and Grails interactive console to create or generate all required components. Type this Grails command to create a new Grails 4 web application.

grails create-app com.djamware.grails-crud

CLI has created a new Grails 4 web application with the name `grails-crud` and package name `com.djamware`. Next, go to the newly created Grails application folder.

cd ./grails-crud

Type this CLI to enter the Grails 4 interactive console.

grails

In the Grails interactive console type this command to see all available commands.

help

Here they are the list of available Grails commands.

Usage (optionals marked with *):'
grails [environment]* [target] [arguments]*'

| Examples:
$ grails dev run-app
$ grails create-app books

| Available Commands (type grails help 'command-name' for more info):
| Command Name                          Command Description
----------------------------------------------------------------------------------------------------
assemble                                Creates a JAR or WAR archive for production deployment
bug-report                              Creates a zip file that can be attached to issue reports for the current project
clean                                   Cleans a Grails application's compiled sources
compile                                 Compiles a Grails application
console                                 Runs the Grails interactive console
create-command                          Creates an Application Command
create-controller                       Creates a controller
create-domain-class                     Creates a Domain Class
create-functional-test                  Creates a Geb Functional Test
create-integration-test                 Creates an integration test
create-interceptor                      Creates an interceptor
create-scaffold-controller              Creates a scaffolded controller
create-script                           Creates a Grails script
create-service                          Creates a Service
create-taglib                           Creates a Tag Library
create-unit-test                        Creates a unit test
dependency-report                       Prints out the Grails application's dependencies
generate-all                            Generates a controller that performs CRUD operations and the associated views
generate-async-controller               Generates an asynchronous controller that performs CRUD operations
generate-controller                     Generates a controller that performs CRUD operations
generate-views                          Generates GSP views for the specified domain class
gradle                                  Allows running of Gradle tasks
help                                    Prints help information for a specific command
install-templates                       Installs scaffolding templates that use f:all to render properties
list-plugins                            Lists available plugins from the Plugin Repository
open                                    Opens a file in the project
plugin-info                             Prints information about the given plugin
run-app                                 Runs a Grails application
run-command                             Executes Grails commands
run-script                              Executes Groovy scripts in a Grails context
schema-export                           Creates a DDL file of the database schema
shell                                   Runs the Grails interactive shell
stats                                   Prints statistics about the project
stop-app                                Stops the running Grails application
test-app                                Runs the applications tests
url-mappings-report                     Prints out a report of the project's URL mappings

| Detailed usage with help [command]


Step #3. Create a Grails 4 Domain Class

We will create 2 domain classes that related to each other. In the Grails interactive console, we can create the Grails domain classes/entities/models by type these commands.

create-domain-class com.djamware.Team
create-domain-class com.djamware.Player

The relationship between those domain classes is Team has many Players and players belongs to Team. Next, open and edit `src/grails-app/domain/com/djamware/Team.groovy` then add these fields or variables inside class body.

String name
String city
String stadium
String logo
String manager
static hasMany = [players: Player]

It has 5 fields/variables with String types and a relationship with Player domain class. Next, add the constraint that use as a basic field validation.

static constraints = {
    name size: 5..40, blank: false, unique: true
    city size: 5..30, blank: false
    stadium size: 5..30, blank: false
    logo size: 5..255, blank: false
    manager size: 5..30, blank: false
}

Add this method to display the name of the team instead of the class name when this domain called.

String toString() {
    name
}

Next, open and edit `src/grails-app/domain/com/djamware/Player.groovy` then add these lines of fields or variables inside the class body.

static belongsTo = [team: Team]
String name
Integer age
String position

It has 3 fields/variables with type String and Integer and a relationship with Team domain class. Next, add the constraint that uses as a basic field validation.

static constraints = {
    name size: 5..40, blank: false
    age min: 16
    position size: 5..40, blank: false
}

Add this method to display the name of the player instead of the class name when this domain called.

String toString() {
    name
}


Step #4. Generate Grails 4 Controllers and Views

In Grails, you don't need to create one by one for each controller and view. Just using a single command in the Grails interactive console, will generate all required controllers and views including their unit testing. Type this command in the Grails interactive console to generate all controllers and views.

generate-all com.djamware.Team
generate-all com.djamware.Player

Now, you have each controller and views for the Team and Player domain. Because we are using String for the logo field image URL, we need to modify the Show team view to show the logo image. Open and edit `src/grails-app/views/team/Show.gsp` then modify the <f:display bean="team" /> to be like this.

<f:display bean="team" except="logo" />

Add a line after that to display the image from the URL of logo data.

<g:img uri="${team?.logo}"/>


Step #5. Run and Test Grails 4 CRUD Web Application

Still in the Grails 4 interactive console, we will run this Grails 4 application from there. We don't need to run the database, because it's already embedded in this Grails application. Type this command to run it.

run-app

Open your favorite browser then go to `http://localhost:8080` and you will see this Grails 4 web application.

Grails 4 Tutorial: Easy to Build CRUD Web Application - Grails Home
Grails 4 Tutorial: Easy to Build CRUD Web Application - List
Grails 4 Tutorial: Easy to Build CRUD Web Application - Create
Grails 4 Tutorial: Easy to Build CRUD Web Application - Show

That it's, Grails 4 Tutorial: Easy to Build CRUD Web Application. You can get the full working source code in our GitHub.

That just the basic. If you need more deep learning about Groovy and Grails you can take the following cheap course:

Thanks!