You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This guide walks you through the process of creating an application that accesses document-based data through a hypermedia-based RESTful front end.
What you’ll build
You’ll build a Spring application that let’s you create and retrieve Person objects stored in a MongoDBNoSQL database using Spring Data REST. Spring Data REST takes the features of Spring HATEOAS and Spring Data MongoDB and combines them together automatically.
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.
Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-accessing-mongodb-data-rest.git
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.
Build with Maven
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 Maven is included here. If you’re not familiar with Maven, refer to 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/java/hello on *nix systems:
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.
The Person has a first name and a last name. There is also an id object that is configured to be automatically generated so you don’t have to deal with that.
This repository is an interface and will allow you to perform various operations involving Person objects. It gets these operations by extending MongoRepository, which in turn extends the PagingAndSortingRepository interface defined in Spring Data Commons.
At runtime, Spring Data REST will create an implementation of this interface automatically. Then it will use the @RepositoryRestResource annotation to direct Spring MVC to create RESTful endpoints at /people.
@RepositoryRestResource is not required for a repository to be exported. It is only used to change the export details, such as using /people instead of the default value of /persons.
Here you have also defined a custom query to retrieve a list of Person objects based on the lastName. You’ll see how to invoke it further down in this guide.
Spring Boot by default attempts to connect to a locally hosted instance of MongoDB. Read the reference docs for details on pointing your app to an instance of MongoDB hosted elsewhere.
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.
@SpringBootApplication is a convenience annotation that adds all of the following:
@Configuration tags the class as a source of bean definitions for the application context.
@EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
@ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.
The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.
Build an executable JAR
You can run the application from the command line with Gradle or Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you are using Gradle, you can run the application using ./gradlew bootRun. Or you can build the JAR file using ./gradlew build. Then you can run the JAR file:
If you are using Maven, you can run the application using ./mvnw spring-boot:run. Or you can build the JAR file with ./mvnw clean package. Then you can run the JAR file:
Here you get a first glimpse of what this server has to offer. There is a people link located at http://localhost:8080/people. It has some options such as ?page, ?size, and ?sort.
Spring Data REST uses the HAL format for JSON output. It is flexible and offers a convenient way to supply links adjacent to the data that is served.
There are currently no elements and hence no pages. Time to create a new Person!
If you run this guide multiple times, there may be left over data. Refer to the MongoDB shell quick reference to find commands to find and drop your database if you need a fresh start.
-i ensures you can see the response message including the headers. The URI of the newly created Person is shown
-X POST signals this a POST used to create a new entry
-H "Content-Type:application/json" sets the content type so the application knows the payload contains a JSON object
-d '{ "firstName" : "Frodo", "lastName" : "Baggins" }' is the data being sent
Notice how the previous POST operation includes a Location header. This contains the URI of the newly created resource. Spring Data REST also has two methods on RepositoryRestConfiguration.setReturnBodyOnCreate(…) and setReturnBodyOnUpdate(…) which you can use to configure the framework to immediately return the representation of the resource just created/updated.
The persons object contains a list with Frodo. Notice how it includes a self link. Spring Data REST also uses Evo Inflector to pluralize the name of the entity for groupings.
This might appear to be purely web based, but behind the scenes, it is talking to the MongoDB database you started.
In this guide, there is only one domain object. With a more complex system where domain objects are related to each other, Spring Data REST will render additional links to help navigate to connected records.
You can see the URL for the query including the HTTP query parameter name. If you’ll notice, this matches the @Param("name") annotation embedded in the interface.
Because you defined it to return List<Person> in the code, it will return all of the results. If you had defined it only return Person, it will pick one of the Person objects to return. Since this can be unpredictable, you probably don’t want to do that for queries that can return multiple entries.
You can also issue PUT, PATCH, and DELETE REST calls to either replace, update, or delete existing records.
A very convenient aspect of this hypermedia-driven interface is how you can discover all the RESTful endpoints using curl (or whatever REST client you are using). There is no need to exchange a formal contract or interface document with your customers.
Summary
Congratulations! You’ve just developed an application with a hypermedia-based RESTful front end and a MongoDB-based back end.
I have query. How can we add custom logic in this method List findByLastName(@param("name") String name);
Currently there is no controller. Spring is implementing this method.
I have to create a method to perform the update after doing some validation. How can i implement?
Any suggestion.
Thanks
Accessing MongoDB Data with REST
This guide walks you through the process of creating an application that accesses document-based data through a hypermedia-based RESTful front end.
What you’ll build
You’ll build a Spring application that let’s you create and retrieve
Person
objects stored in a MongoDB NoSQL database using Spring Data REST. Spring Data REST takes the features of Spring HATEOAS and Spring Data MongoDB and combines them together automatically.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 Build with Gradle.
To skip the basics, do the following:
git clone https://github.com/spring-guides/gs-accessing-mongodb-data-rest.git
gs-accessing-mongodb-data-rest/initial
When you’re finished, you can check your results against the code in
gs-accessing-mongodb-data-rest/complete
.Build with Gradle
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/java/hello
on *nix systems:Create a Gradle build file
Below is the initial Gradle build file.
build.gradle
The Spring Boot gradle plugin provides many convenient features:
public static void main()
method to flag as a runnable class.Build with Maven
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 Maven is included here. If you’re not familiar with Maven, refer to 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/java/hello
on *nix systems:pom.xml
The Spring Boot Maven plugin provides many convenient features:
public static void main()
method to flag as a runnable class.Build with your IDE
Install and launch MongoDB
For this guide to work, you must stand up a local MongoDB server.
On a Mac OS X machine with homebrew, just do this:
More installation options are found at http://docs.mongodb.org/manual/installation/.
After installing it, you need to launch the mongo daemon.
The MongoDB client that is also installed can be started from another terminal window by typing
mongo
.Create a domain object
Create a new domain object to present a person.
src/main/java/hello/Person.java
The
Person
has a first name and a last name. There is also an id object that is configured to be automatically generated so you don’t have to deal with that.Create a Person repository
Next you need to create a simple repository.
src/main/java/hello/PersonRepository.java
This repository is an interface and will allow you to perform various operations involving
Person
objects. It gets these operations by extendingMongoRepository
, which in turn extends the PagingAndSortingRepository interface defined in Spring Data Commons.At runtime, Spring Data REST will create an implementation of this interface automatically. Then it will use the @RepositoryRestResource annotation to direct Spring MVC to create RESTful endpoints at
/people
.Here you have also defined a custom query to retrieve a list of Person objects based on the lastName. You’ll see how to invoke it further down in this guide.
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/java/hello/Application.java
@SpringBootApplication
is a convenience annotation that adds all of the following:@Configuration
tags the class as a source of bean definitions for the application context.@EnableAutoConfiguration
tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.@EnableWebMvc
for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up aDispatcherServlet
.@ComponentScan
tells Spring to look for other components, configurations, and services in thehello
package, allowing it to find the controllers.The
main()
method uses Spring Boot’sSpringApplication.run()
method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.Build an executable JAR
You can run the application from the command line with Gradle or Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you are using Gradle, you can run the application using
./gradlew bootRun
. Or you can build the JAR file using./gradlew build
. Then you can run the JAR file:If you are using Maven, you can run the application using
./mvnw spring-boot:run
. Or you can build the JAR file with./mvnw clean package
. Then you can run the JAR file:Logging output is displayed. The service should be up and running within a few seconds.
Test the application
Now that the application is running, you can test it. You can use any REST client you wish. The following examples use the *nix tool
curl
.First you want to see the top level service.
Here you get a first glimpse of what this server has to offer. There is a people link located at http://localhost:8080/people. It has some options such as
?page
,?size
, and?sort
.Spring Data REST uses the HAL format for JSON output. It is flexible and offers a convenient way to supply links adjacent to the data that is served.
There are currently no elements and hence no pages. Time to create a new
Person
!-i
ensures you can see the response message including the headers. The URI of the newly createdPerson
is shown-X POST
signals this a POST used to create a new entry-H "Content-Type:application/json"
sets the content type so the application knows the payload contains a JSON object-d '{ "firstName" : "Frodo", "lastName" : "Baggins" }'
is the data being sentFrom this you can query for all people:
The persons object contains a list with Frodo. Notice how it includes a self link. Spring Data REST also uses Evo Inflector to pluralize the name of the entity for groupings.
You can query directly for the individual record:
In this guide, there is only one domain object. With a more complex system where domain objects are related to each other, Spring Data REST will render additional links to help navigate to connected records.
Find all the custom queries:
You can see the URL for the query including the HTTP query parameter
name
. If you’ll notice, this matches the@Param("name")
annotation embedded in the interface.To use the findByLastName query, do this:
Because you defined it to return
List<Person>
in the code, it will return all of the results. If you had defined it only returnPerson
, it will pick one of the Person objects to return. Since this can be unpredictable, you probably don’t want to do that for queries that can return multiple entries.You can also issue
PUT
,PATCH
, andDELETE
REST calls to either replace, update, or delete existing records.You can delete records:
A very convenient aspect of this hypermedia-driven interface is how you can discover all the RESTful endpoints using
curl
(or whatever REST client you are using). There is no need to exchange a formal contract or interface document with your customers.Summary
Congratulations! You’ve just developed an application with a hypermedia-based RESTful front end and a MongoDB-based back end.
See Also
The following guides may also be helpful:
The text was updated successfully, but these errors were encountered: