Choosing the right programming language for your project is a big deal. While it might be possible to use your favorite one over and over again for any project there is, that can be sometimes counterproductive as some languages and frameworks are well suited for specific project types. Games development might be easier with C# or C++ while big enterprise applications are more likely to be written in Java. Let’s talk about Grails and how you can benefit from it.

Grails

It is an awesome framework. I have worked on several small and big Grails projects, and the same patterns (problems/ surprises/ benefits) appeared on each of them.

When NOT to use Grails:

  • You don’t know yet how your project will scale up
    Adding simple controllers or services is fine, but tripling the whole codebase and adding numerous data sources and different output types and services can be frustrating using a language that’s motto is “Convention over Configuration”. More and more complicated project will get, more conventions you need to (or want to) break, which comes up with many work-arounds -> thus problems.
  • Your project will keep changing a lot – and you already know it
    Refactoring is a pain if you use all that language offers. Writing dynamic variables do not hold references, so can hardly be refactored automatically. You will remember it next time you get IllegalArgumentException or NullPointerException or …

When DO use Grails:

  • You need your first demo/ POC by the end of the day.
    It is incredible how much you can do with Grails in first stages of the project. You can build whole application in matter of minutes and have working RESTful services including admin view and database in matter if hours. Of course at some point, it gets slower than you would expect, but you met that deadline for first version, so you have that going for you, which is nice.
  • You want simple hassle free project
    Grails contains many features that simplify your work. No need for getters and setters/ constructors/ extensive class configurations and many more features that will minimize your code just by using conventions. You can enjoy Spring-powered dependency injection with even simplified config compared to Java. No need for separate development server, because Grails contains it’s own integrated web server for development with continuous deployment…

Create your first Grails project

After downloading and installing the framework (from official sie or preferably via SdkMan to manage your versions easily), go to your workspace and just type

grails create-app SampleProject

and your first empty project is ready.
Now navigate into project and start-up Grails console

cd SampleProject
grails

and create domain, service for that domain and also a controller for it

create-domain-class User
create-controller User
create-service User

Now go to your favorite IDE (there is dedicated eclipse based ToolSuite available) and import newly created project.

Connect Database to your project

Let’s create new database for our project, let’s name it “sample”, with mysql.
mysql> create database sample

connect database in conf/DataSource.groovy like this:

environments {
  development {
    dataSource {
      dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
      url = "jdbc:mysql://localhost/sample"
      dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
      driverClassName = "com.mysql.jdbc.Driver"
      username = "root"
      password = ""
    }
  }
...
}

and in conf/BuildConfig.groovy under dependencies uncomment (or add if it is not there)
runtime 'mysql:mysql-connector-java:5.1.29'

and that is it.

Add some simple RESTful service

add new attributes to User domain. Id or version is not needed as that will be used as default for every domain class.

String firstName
String lastName

edit UserService.groovy to add 2 new methods. Storing and retrieving user from DB.

def add(firstName, lastName) { //no restrictions here on data types
  def user = new User(firstName: firstName, lastName: lastName) 
    //this constructor does not need to be defined in User domain
  user.save() 
    //this is also return statement, so saved user will be returned
}
def find(name) {
  User.findAllByFirstNameLikeOrLastNameLike(name, name) 
    //GORM will create query out of this, returning the list of Users
}

and update UserController to look like this:

class UserController {

  def userService //this will automatically inject UserService

  def add() {
    def user = userService.add(params.firstName, params.lastName) 
      //calling our service
    user ? render (text: "OK") : render (status: 400) 
      //if user is returned, render HTTP status 200 and text "OK" otherwise just return status 400
  }

  def show() {
    def users = userService.find(params.query)
    if (users?.size() > 0) {
      render users as JSON 
        //grails.converters.JSON will convert object into JSON format. 
        //you can also use XML or define own marshaller
    } else {
      render status: 400
    }
  }
}

This is enough to have functional RESTful API. We will now start the application by

grails run-app

No tomcat server installation and configuration is required here. It should just end up with something like

|Server running. Browse to http://localhost:8080/SampleProject

By going to that link, you will see Welcome Page like this:
Grails Welcome PA

Because we did not specify what kind of request we need to make for any of our calls, lets just paste this into browser to add new user:

http://localhost:8080/SampleProject/User/add?firstName=first&lastName=last

url consists of {your app url}/{name of the controller without the keyword “Controller”}/{name of the method}
and because we were using “params” in our methods, inpout should be url encoded

In order to search for our newly created user, type:

http://localhost:8080/SampleProject/User/show?query=last

to retrieve the user JSON:

[
    {
        "class": "sampleproject.User",
        "id": 1,
        "firstName": "first",
        "lastName": "last"
    }
]

And that is it! Simple in few steps. really easy to quickly prototype applications.

Facebook Comments
Grails – Groovy On Rails first project
Tagged on:             

One thought on “Grails – Groovy On Rails first project

Leave a Reply

Your email address will not be published. Required fields are marked *