This guide walks you through the process of creating a Spring Boot application that uses Grails Object Relational Mapper (GORM) and MongoDB for persistence. The application uses to GORM for MongoDB plugin.

What you’ll build

You’ll build a Spring application that persists geospatial data to MongoDB using GORM.

This guide only uses uses the Grails GORM library. You aren’t required to use the full Grails web stack.

What you’ll need

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Set up the project.

To skip the basics, do the following:

When you’re finished, you can check your results against the code in gs-accessing-data-gorm-mongodb/complete.

Set up the project

First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with Gradle and Maven is included here. If you’re not familiar with either, refer to Building Java Projects with Gradle or Building Java Projects with Maven.

Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/groovy/cities on *nix systems:

└── src
    └── main
        └── groovy
            └── cities

Create a Gradle build file

build.gradle

buildscript {
    repositories {
    mavenLocal()
        mavenCentral()
        maven { url "https://repo.spring.io/milestone" }
        maven { url "https://repo.spring.io/libs-release" }
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.10.RELEASE")
    }
}

apply plugin: 'groovy'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-spring-boot-gorm-mongodb'
    version =  '0.1.0'
}

repositories {
    mavenLocal()
    mavenCentral()
    mavenLocal()
        mavenCentral()
    maven { url "https://repo.spring.io/milestone" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.grails:gorm-mongodb-spring-boot:1.1.0.RELEASE")
    runtime("org.springframework.boot:spring-boot-starter-data-mongodb")
    testCompile("junit:junit")
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
}

The Spring Boot gradle plugin provides many convenient features:

  • It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.

  • It searches for the public static void main() method to flag as a runnable class.

  • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.

Create a GORM entity

In this example, we model a simple City entity using GORM:

src/main/groovy/cities/City.groovy

package cities

import grails.persistence.*
import grails.mongodb.geo.*
import org.bson.types.ObjectId

@Entity
class City {
    ObjectId id
    String name
    Point location

    static constraints = {
        name blank:false
        location nullable:false
    }

    static mapping = {
        location geoIndex:'2dsphere'
    }
}

The constraint block defines any validation rules. In this case, we ensure that the name cannot be blank and the location cannot be null.

The mapping block specifies that the location property should be indexed using a geospatial 2dsphere index.

The location property is a grails.mongodb.geo.Point that gets persisted to MongoDB as a GeoJSON Point.

Create a resource controller

Create a controller for your Groovy-based Spring application:

src/main/groovy/cities/CityController.groovy

package cities

import com.mongodb.BasicDBObject
import javax.annotation.PostConstruct;
import org.springframework.web.bind.annotation.*
import org.springframework.http.*
import static org.springframework.web.bind.annotation.RequestMethod.*
import grails.mongodb.geo.*

@RestController
class CityController {

    @RequestMapping(value="/", method = GET)
    List index() {
        City.list().collect { [name: it.name] }
    }

    @RequestMapping(value="/near/{cityName}", method = GET)
    ResponseEntity near(@PathVariable String cityName) {
        def city = City.where { name == cityName }.find()
        if(city) {
            List<City> closest = City.findAllByLocationNear(city.location)
            return new ResponseEntity([name: closest[1].name], HttpStatus.OK)
        }
        else {
            return new ResponseEntity(HttpStatus.NOT_FOUND)
        }
    }

    @PostConstruct
    void populateCities() {
        City.withTransaction{
            City.collection.remove(new BasicDBObject())
            City.saveAll(
                [ new City( name:"London",
                            location: Point.valueOf([-0.125487, 51.508515])),
                  new City( name:"Paris",
                            location: Point.valueOf([2.352222, 48.856614])),
                  new City( name:"New York",
                            location: Point.valueOf([-74.005973, 40.714353])),
                  new City( name:"San Francisco",
                            location: Point.valueOf([-122.419416, 37.774929])) ]
            )
        }
    }
}

The above example defines two REST endpoints:

  • The index endpoint list all the known cities

  • The near endpoint finds the city nearest to the specified city

The populateCities method is run at startup due to the presence of the @PostConstruct annotation. The method provides some initial data for the application to operate on. Notice how each city is provided a Point instance with the location specified in longitude / latitude order:

@PostConstruct
void populateCities() {
    City.withTransaction{
        City.collection.remove(new BasicDBObject())
        City.saveAll(
            [ new City(name:"London",
                       location: Point.valueOf( [-0.125487, 51.508515] ) ),
              ...
              new City(name:"San Francisco",
                       location: Point.valueOf( [-122.419416, 37.774929] ) ) ]
        )
    }
}

The near method takes the city name as parameter and then proceeds to find the nearest cities. Note that the first entry in the reult will be the city queried itself, so an index of 1 is used to find the closest city:

@RequestMapping(value="/near/{cityName}", method = GET)
ResponseEntity near(@PathVariable String cityName) {
    def city = City.findByName(cityName)
    if(city) {
        List<City> closest = City.findAllByLocationNear(city.location)
        return new ResponseEntity([name: closest[1].name], HttpStatus.OK)
    }
    ...
}

Further down in the guide, you’ll see how to run the application.

Make the application executable

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.

src/main/groovy/cities/Application.groovy

package cities

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.ComponentScan

@EnableAutoConfiguration
@ComponentScan
class Application {
    static void main(String[] args) {
        SpringApplication.run Application, args
    }
}

The main() method defers to the SpringApplication helper class, providing Application.class as an argument to its run() method. This tells Spring to read the annotation metadata from Application and to manage it as a component in the Spring application context.

The @ComponentScan annotation tells Spring to search recursively through the hello package and its children for classes marked directly or indirectly with Spring’s @Component annotation. This directive ensures that Spring finds and registers the GreetingController, because it is marked with @Controller, which in turn is a kind of @Component annotation.

The @EnableAutoConfiguration annotation switches on reasonable default behaviors based on the content of your classpath. For example, because the application depends on the embeddable version of Tomcat (tomcat-embed-core.jar), a Tomcat server is set up and configured with reasonable defaults on your behalf. And because the application also depends on Spring MVC (spring-webmvc.jar), a Spring MVC DispatcherServlet is configured and registered for you — no web.xml necessary! Auto-configuration is a powerful, flexible mechanism. See the API documentation for further details.

Build an executable JAR

If you are using Gradle, you can run the application using ./gradlew bootRun.

You can build a single executable JAR file that contains all the necessary dependencies, classes, and resources. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

./gradlew build

Then you can run the JAR file:

java -jar build/libs/gs-accessing-data-gorm-mongodb-0.1.0.jar

If you are using Maven, you can run the application using mvn spring-boot:run. Or you can build the JAR file with mvn clean package and run the JAR by typing:

java -jar target/gs-accessing-data-gorm-mongodb-0.1.0.jar
The procedure above will create a runnable JAR. You can also opt to build a classic WAR file instead.

Test the application

With the application started, you can create a new person by submitting a POST request. For example using the *nix curl tool:

$ curl -i http://localhost:8080/

This results in the following response with the list of cities in JSON format:

$ curl -i http://localhost:8080/
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 21 Mar 2014 07:52:34 GMT

[{"name":"London"},{"name":"Paris"},{"name":"New York"},{"name":"San Francisco"}]

You can then submit a GET request to the near endpoint to find out which city is nearest to a specified city:

$ curl -i http://localhost:8080/near/Paris
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 21 Mar 2014 07:53:47 GMT

{"name":"London"}
This RESTful front end was coded for demonstration purposes. You can plug in GORM wherever you need it for your application.

Groovy Script Support

The previous example required you to setup a Gradle or Maven build, but you can also use GORM in a simple Groovy script.

As an example, create a new file called app.groovy and put the following code in it:

app.groovy

@Grab("org.grails:gorm-mongodb-spring-boot:1.1.0.RELEASE")
@Grab("org.mongodb:mongo-java-driver:2.12.2")
import grails.persistence.*
import grails.mongodb.geo.*
import org.bson.types.ObjectId
import com.mongodb.BasicDBObject
import static org.springframework.web.bind.annotation.RequestMethod.*

@RestController
class CityController {

    @RequestMapping(value="/", method = GET)
    List index() {
        City.list().collect { [name: it.name] }
    }

    @RequestMapping(value="/near/{cityName}", method = GET)
    ResponseEntity near(@PathVariable String cityName) {
        def city = City.where { name == cityName }.find()
        if(city) {
            List<City> closest = City.findAllByLocationNear(city.location)
            return new ResponseEntity([name: closest[1].name], HttpStatus.OK)
        }
        else {
            return new ResponseEntity(HttpStatus.NOT_FOUND)
        }
    }

    @PostConstruct
    void populateCities() {
        City.withTransaction{
            City.collection.remove(new BasicDBObject())
            City.saveAll(
                [ new City(name:"London",
                           location: Point.valueOf([-0.125487, 51.508515])),
                  new City(name:"Paris",
                           location: Point.valueOf([2.352222, 48.856614])),
                  new City(name:"New York",
                           location: Point.valueOf([-74.005973, 40.714353])),
                  new City(name:"San Francisco",
                           location: Point.valueOf([-122.419416, 37.774929]))
                ]
            )
        }
    }
}

@Entity
class City {
    ObjectId id
    String name
    Point location

    static constraints = {
        name blank:false
        location nullable:false
    }

    static mapping = {
        location geoIndex:'2dsphere'
    }
}
It doesn’t matter where the file is.

Run it as follows:

$ spring run app.groovy
This assumes you shut down the previous application, to avoid a port collision.

Then simply follow the previous steps to test the application.

Configuring the MongoDB Connection

To configure the MongoDB connection settings you can use the application’s application.yml file:

src/main/resources/application.yml

spring:
    mongodb:
        host: "localhost"
        databaseName: "citydb"
        options:
            connectionsPerHost: 20

The available configuration options are the same as those provided by the MongoDB plugin for Grails.

Alternatively, if you have custom configuration requirements then you can configure a Spring bean of type com.mongodb.Mongo in your application.

Summary

Congratulations! You’ve just developed a Spring application using GORM for MongoDB data access as well as a RESTful front end!