Building CRUD Web Application using Grails 4 and MongoDB Easily

by Didin J. on Jul 24, 2019 Building CRUD Web Application using Grails 4 and MongoDB Easily

A comprehensive step by step tutorial on building CRUD web application using Grails 4 and MongoDB easily

A comprehensive step by step tutorial on building CRUD web application using Grails 4 and MongoDB easily. Starting from creating a new Grails 4 project, setting up MongoDB plugin and connection, creating entities, controllers, views, and run/test the complete Grails 4 and MongoDB application.

Table of Contents:

In this tutorial, we will use more than one entity that related each other using one-to-one, one-to-many, and many-to-many relationships. All relationship did use Grails 4 domain class. For more detail, you can see this entity relationship diagram.

Building CRUD Web Application using Grails 4 and MongoDB Easily - ERD

Above diagram describes a one-to-one relationship between the Teacher and the Lesson, a one-to-many between the Classroom and the Students, and a many-to-many relationship between the Students and the Lessons. Using that relational Domain class, we will build the CRUD (create, read, update, delete) operational using the web form.

The following tools, frameworks, and libraries are required for this tutorial:

  1. JDK 1.8
  2. Grails 4.0.0
  3. MongoDB
  4. Grails MongoDB plugin
  5. Terminal or Command Line
  6. Text Editor or IDE

Before the move to the main steps, make sure you have install JDK 1.8, MongoDB.


Install and Create Grails 4 Web Application

There are various and different ways to install the Grails web application depends on the operating system. If you are using macOS terminal, the easiest way to install Grails 4 is using the SDKMan. Simply run this command from the terminal to install it.

sdk install grails

Or you can use a specific version using this command.

sdk install grails 4.0.0

The Groovy language will be included in the Grails installation bundle. For the Windows platform, just download the compressed Grails 4 binary from the Grails download page then extract that Grails 4 folder to the specific directory where ever you like. Add the Grails 4 folder to the environment variable and the path to make Grails command available in the Windows Command line. To check the installed Grails version type this command.

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

Next, create a new Grails 4 application by typing this command.

grails create-app grails4-crud

To working in the Grails interactive console, type this command after go to the newly created Grails 4 application folder.

cd ./grails4-crud
grails

Run the Grails 4 for the first time by typing this command from the Grails interactive console.

run-app

Open the browser then point to `http://localhost:8080` and you will see this Grails 4 application home page.

Building CRUD Web Application using Grails 4 and MongoDB Easily - Home Page


Install and Configure MongoDB Plugin

We will use MongoDB as the primary Datastore for this Grails 4 application. So, we have to disable or uninstall the Hibernate plugin from this application. Open the Grails 4 project in your IDE or text editor then open and edit `build.gradle` file. Comment out the Hibernate plugin and related.

buildscript {
    ...
    dependencies {
        classpath "org.grails:grails-gradle-plugin:$grailsVersion"
        // classpath "org.grails.plugins:hibernate5:7.0.0"
        classpath "gradle.plugin.com.github.erdi.webdriver-binaries:webdriver-binaries-gradle-plugin:2.0"
        classpath "com.bertramlabs.plugins:asset-pipeline-gradle:3.0.10"
    }
}

dependencies {
    ...
    // compile "org.grails.plugins:hibernate5"
    // compile "org.hibernate:hibernate-core:5.4.0.Final"
    ...
    // runtime "com.h2database:h2"
    ...
}

Then add Grails MongoDB plugin to that file on the dependencies bracket.

dependencies {
    ...
    compile "org.grails.plugins:mongodb:7.0.0"
    ...
}

Next, compile the Grails 4 application using this command inside the Grails interactive console.

compile

Next, configure the MongoDB connection by open and edit `grails-app/conf/application.yml` then comment out the Hibernate and H2 database connection while adding the connection for the MongoDB.

# hibernate:
#     cache:
#         queries: false
#         use_second_level_cache: false
#         use_query_cache: false
# dataSource:
#     pooled: true
#     jmxExport: true
#     driverClassName: org.h2.Driver
#     username: sa
#     password: ''

environments:
    # development:
    #     dataSource:
    #         dbCreate: create-drop
    #         url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    # test:
    #     dataSource:
    #         dbCreate: update
    #         url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    # production:
    #     dataSource:
    #         dbCreate: none
    #         url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    #         properties:
    #             jmxEnabled: true
    #             initialSize: 5
    #             maxActive: 50
    #             minIdle: 5
    #             maxIdle: 25
    #             maxWait: 10000
    #             maxAge: 600000
    #             timeBetweenEvictionRunsMillis: 5000
    #             minEvictableIdleTimeMillis: 60000
    #             validationQuery: SELECT 1
    #             validationQueryTimeout: 3
    #             validationInterval: 15000
    #             testOnBorrow: true
    #             testWhileIdle: true
    #             testOnReturn: false
    #             jdbcInterceptors: ConnectionState
    #             defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
    development:
        grails:
            mongodb:
                host: "localhost"
                port: 27017
                username: ""
                password: ""
                databaseName: "grails4-crud"
    production:
        grails:
            mongodb:
                host: "localhost"
                port: 27017
                username: ""
                password: ""
                databaseName: "grails4-crud"


Create the Grails 4 Domains

One of the Grails great features is building entities easily just by create domain class. Right here, we will translate the Entity Relationship Diagram to the Grails 4 domain class. For that, type these commands in the Grails 4 interactive console.

create-domain-class grails4.crud.Teacher
create-domain-class grails4.crud.Student
create-domain-class grails4.crud.Lesson
create-domain-class grails4.crud.Classroom

Next, open and edit `grails-app/domain/grails4/crud/Teacher.groovy` then insert these lines of field codes inside the class bracket.

String teacherName
static hasOne = [lesson: Lesson]

That field has a one-to-one relationship with the Lesson class. Next, add the mapping method after the constraint method to give an index to this MongoDB collection.

static mapping = {
    teacherName index: true
}

Add the blank constraint for the lesson field otherwise, it will be mandatory in the CRUD views.

static constraints = {
    lesson blank: true, nullable: true
}

Also, add these lines of Groovy codes to make the Teacher domain showed up as the teacher name in the views.

String toString() {
    teacherName
}

Next, open and edit `grails-app/domain/grails4/crud/Lesson.groovy` then insert these lines of field codes inside the class bracket.

String lessonName
Integer lessonHour
Teacher teacher
static hasMany = [students: Student]

That field has a one-to-one relationship with the Teacher class, a many-to-many relationship with the Student class. Next, add the mapping method after the constraint method to give an index to this MongoDB collection.

static mapping = {
    lessonName index: true
}

Add the blank constraint for the teacher field otherwise, it will be mandatory in the CRUD views.

static constraints = {
    teacher blank: true, nullable: true
}

Also, add these lines of Groovy codes to make the Lesson domain showed up as the lesson name in the views.

String toString() {
    lessonName
}

Next, open and edit `grails-app/domain/grails4/crud/Student.groovy` then insert these lines of field codes inside the class bracket.

String studentName
static hasMany = [lessons: Lesson]
static belongsTo = [Classroom]

That field has a many-to-many relationship with the Lesson class, a one-to-many relationship with the Classroom class. Next, add the mapping method after the constraint method to give an index to this MongoDB collection.

static mapping = {
    studentName index: true
}

Add these lines of Groovy codes to make the Student domain showed up as the student name in the views.

String toString() {
    studentName
}

Next, open and edit `grails-app/domain/grails4/crud/Classroom.groovy` then insert these lines of field codes inside the class bracket.

String classroomName
static hasMany = [students: Student]

That field has a one-to-many relationship with the Student class. Next, add the mapping method after the constraint method to give an index to this MongoDB collection.

static mapping = {
    classroomName index: true
}

Add these lines of Groovy codes to make the Classroom domain showed up as the classroom name in the views.

String toString() {
    classroomName
}

That domain classes will generate ID with an auto-increment number. You will see later in the MongoDB that ID type will be `NumberLong` type. Optionally, if you want to use standard MongoDB Object ID for the ID, just add this line in the fields.

ObjectId id

And import that object.

import org.bson.types.ObjectId


Generate the Grails 4 Controller and View for All Domains

The quickest way to create controllers and views are generated using this command in the Grails 4 interactive console.

generate-all grails4.crud.Teacher
generate-all grails4.crud.Lesson
generate-all grails4.crud.Student
generate-all grails4.crud.Classroom

Now, you have a complete CRUD (Create, Read, Update, Delete) web application scaffolding. You may check the controller Groovy file and GSP file (view) to learn how the scaffolding of the Grails 4 web application working.


Run and Test the Complete Grails 4 and MongoDB CRUD Web Application

Before running the application, make sure you have run the MongoDB daemon. If MongoDB daemon not running automatically, you can run it manually using this command in the different terminal tab.

mongod

Next, you can start the Grails 4 application inside the Grails 4 interactive console by just typing this command.

run-app

And here we go, in the browser, you can point to `http://localhost:8080/` and you will see the previous Grails 4 page with additional Grails 4 controller link.

Building CRUD Web Application using Grails 4 and MongoDB Easily - Home Page with Controller list
Building CRUD Web Application using Grails 4 and MongoDB Easily - Add Data
Building CRUD Web Application using Grails 4 and MongoDB Easily - Show Data

That it's, the tutorial of building CRUD Web Application using Grails 4 and MongoDB Easily. You can get the full source code from our GitHub.

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

Thanks!

Loading…