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

What you’ll build

You’ll build a Spring application that persists data to an in-memory database 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

  • About 15 minutes

  • A favorite text editor or IDE

  • JDK 1.7 or later

  • Gradle 1.8+

  • You can also import the code from this guide as well as view the web page directly into Spring Tool Suite (STS) and work your way through it from there.

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/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 is included here. Refer to Building Java Projects with Gradle if you have never worked with Gradle before.

Create the directory structure

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

└── src
    └── main
        └── groovy
            └── hello

Create a Gradle build file

Below is the initial Gradle build file. If you are using Spring Tool Suite (STS), you can import the guide directly.

build.gradle

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

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

jar {
    baseName = 'gs-accessing-data-gorm'
    version =  '0.1.0'
}

repositories {
    mavenLocal()
    mavenCentral()
    maven { url "http://repo.spring.io/libs-release" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.grails:gorm-hibernate4-spring-boot:1.1.0.RELEASE")
    runtime("com.h2database:h2")
    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 Person entity using GORM:

src/main/groovy/hello/Person.groovy

package hello

import grails.persistence.*

@Entity
class Person {
    String firstName
    String lastName

    static constraints = {
        firstName blank:false
        lastName blank:false
    }
}

The constraint block defines any validation rules. In this case, the only constraint is that both fields must be provided.

Create a resource controller

Create a controller for your Groovy-based Spring application:

src/main/groovy/hello/GreetingController.groovy

package hello

import org.springframework.web.bind.annotation.*
import org.springframework.http.*
import static org.springframework.web.bind.annotation.RequestMethod.*

@RestController
class GreetingController {

    @RequestMapping(value="/person/greet", method = GET)
    String greet(String firstName) {
        def p = Person.findByFirstName(firstName)
        return p ? "Hello ${p.firstName}!" : "Person not found"
    }

    @RequestMapping(value = '/person/add', method = POST)
    ResponseEntity addPerson(String firstName, String lastName) {
        Person.withTransaction {
            def p = new Person(firstName: firstName, lastName: lastName).save()
            if(p) {
                return new ResponseEntity(HttpStatus.CREATED)
            }
            else {
                return new ResponseEntity(HttpStatus.BAD_REQUEST)
            }
        }
    }

}

The above example defines two REST endpoints:

  • The addPerson endpoint allows the addition of new people

  • The greet endpoint greets a person by their first name.

Further down in the guide, you’ll see how to run the application and create new Person entries.

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/hello/Application.groovy

package hello

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-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-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 -X POST -d "firstName=Homer&lastName=Simpson" http://localhost:8080/person/add

This results in the following response indicating that a resource was created:

HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Content-Length: 0
Date: Wed, 19 Feb 2014 13:21:06 GMT

You can then submit a GET request to the greet endpoint to receive a greeting:

$ curl -i http://localhost:8080/person/greet?firstName=Homer
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/plain;charset=ISO-8859-1
Content-Length: 12
Date: Wed, 19 Feb 2014 13:22:15 GMT

Hello Homer!
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-hibernate4-spring-boot:1.1.0.RELEASE")
@Grab("h2")
import grails.persistence.*
import org.springframework.http.*
import static org.springframework.web.bind.annotation.RequestMethod.*

@RestController
class GreetingController {

    @RequestMapping(value="/person/greet", method = GET)
    String greet(String firstName) {
        def p = Person.findByFirstName(firstName)
        return p ? "Hello ${p.firstName}!" : "Person not found"
    }

    @RequestMapping(value = '/person/add', method = POST)
    ResponseEntity addPerson(String firstName) {
        Person.withTransaction {
            def p = new Person(firstName: firstName).save()
            return new ResponseEntity( p ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST)
        }
    }
}

@Entity
class Person {
    String firstName
}
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 DataSource

The javax.sql.DataSource to be used to create connections can be configured as per the instructions in the Spring Boot user guide.

Summary

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