Sunday, 18 September 2011

Cloud Foundry + Grails + MongoDB: QuickStart

MongoDB is a document database that provides a high performance flexible scheme with a rich document query API.  In this blog I am going to walkthrough building a basic Grails application that uses MongoDB and the process of deploying it to Cloud Foundry.


Grails: Plugin Setup
Grails has a powerful persistence framework known as GORM however by default GORM uses Hibernate to perform object relational mapping into a traditional RDBMS. In this example I am going to show how you can keep the power of GORM however store data into MongoDB.

The first thing you need to do is to uninstall the Hibernate plugin and install the MongoDB plugin instead. Bring up your Grails console and execute:

uninstall-plugin hibernate

install-plugin mongodb

The end goal of this blog is to have our application running on Cloud Foundry so lets also install the Cloud Foundry plugin:

install-plugin cloud-foundry

Grails: Building a CRUD application
Although we are now using the mongodb plugin instead of hibernate, we can still use GORM as normal. To illustrate this I am going to build a basic Grails application.

Lets create a quick domain class that represents a Product:

grails create-domain-class charris.example.Product

I want to keep this simple so lets just add a name field to the Product that must not be null.

package charris.example

class Product {

    String name
           
    static constraints = {
            name blank:false
    }
}

Now we have a domain class, the next step is to create a simple controller that allows CRUD operations on my Product. Open the grails console  and execute:

create-controller charris.example.Product

We can also get Grails to generate the rest of the application components for us by adding the “scaffold” property to the controller:

package charris.example

class ProductController {
            
    // add this line
    def scaffold = Product

}

Creating a Cloud Foundry Service
As Cloud Foundry offers MongoDB as a service, all we need to do is create an instance of MongoDB within our Cloud Foundry account. To do this open the Grails console and execute:

cf-create-service mongodb mongodb

Pushing to Cloud Foundry
Lets push our application to Cloud Foundry.

Open the Grails console within your example project and execute:

cf-push

This command packages up your application and kicks off the process of uploading your application to Cloud Foundry. As part of the process, the command is going to ask you a series of simple questions:

Q1: You running in development …etc? - Basically Grails is asking if it should build the war.  
A: ‘y’

Q2: Application Deployment URL?
A: Enter the URL you would like to deploy this application on.

Q3: Would you like to bind ‘mongodb’?
A: ‘y’

Testing
Open a web browser and hit the URL you entered during the push process. 

Enjoy J

10 comments: