An open API service indexing awesome lists of open source software.

https://github.com/pacphi/spring-boot-mongodb-example

Spring Boot + Spring Data Mongo / REST example
https://github.com/pacphi/spring-boot-mongodb-example

Last synced: about 1 year ago
JSON representation

Spring Boot + Spring Data Mongo / REST example

Awesome Lists containing this project

README

          

---
tags: [spring-data, mongodb]
projects: [spring-data-mongodb]
---
:toc:
:icons: font
:source-highlighter: prettify
:project_id: gs-accessing-data-mongodb
This guide walks you through the process of using http://projects.spring.io/spring-data-mongodb/[Spring Data MongoDB] to build an application that stores data in and retrieves it from http://www.mongodb.org/[MongoDB], a document-based database.

== What you'll build

You will store `Customer` link:/understanding/POJO[POJOs] in a MongoDB database using Spring Data MongoDB.

== What you'll need

:java_version: 1.8
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/prereq_editor_jdk_buildtools.adoc[]

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/how_to_complete_this_guide.adoc[]

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-gradle.adoc[]

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-maven.adoc[]

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/hide-show-sts.adoc[]

[[initial]]
== Install and launch MongoDB
With your project set up, you can install and launch the MongoDB database.

If you are using a Mac with homebrew, this is as simple as:

$ brew install mongodb

With MacPorts:

$ port install mongodb

For other systems with package management, such as Redhat, Ubuntu, Debian, CentOS, and Windows, see instructions at http://docs.mongodb.org/manual/installation/.

After you install MongoDB, launch it in a console window. This command also starts up a server process.

$ mongod

You probably won't see much more than this:

....
all output going to: /usr/local/var/log/mongodb/mongo.log
....

== Define a simple entity
MongoDB is a NoSQL document store. In this example, you store `Customer` objects.

`src/main/java/io/pivotal/customer/Customer.java`
[source,java]
----
include::complete/src/main/java/io/pivotal/customer/Customer.java[]
----

Here you have a `Customer` class with three attributes, `id`, `firstName`, and `lastName`. The `id` is mostly for internal use by MongoDB. You also have a single constructor to populate the entities when creating a new instance.

NOTE: In this guide, the typical getters and setters have been left out for brevity.

`id` fits the standard name for a MongoDB id so it doesn't require any special annotation to tag it for Spring Data MongoDB.

The other two properties, `firstName` and `lastName`, are left unannotated. It is assumed that they'll be mapped to fields that share the same name as the properties themselves.

The convenient `toString()` method will print out the details about a customer.

NOTE: MongoDB stores data in collections. Spring Data MongoDB will map the class `Customer` into a collection called _customer_. If you want to change the name of the collection, you can use Spring Data MongoDB's http://docs.spring.io/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/mapping/Document.html[`@Document`] annotation on the class.

== Create simple queries
Spring Data MongoDB focuses on storing data in MongoDB. It also inherits functionality from the Spring Data Commons project, such as the ability to derive queries. Essentially, you don't have to learn the query language of MongoDB; you can simply write a handful of methods and the queries are written for you.

To see how this works, create a repository interface that queries `Customer` documents.

`src/main/java/io/pivotal/customer/CustomerRepository.java`
[source,java]
----
include::complete/src/main/java/io/pivotal/customer/CustomerRepository.java[]
----

`CustomerRepository` extends the `MongoRepository` interface and plugs in the type of values and id it works with: `Customer` and `String`. Out-of-the-box, this interface comes with many operations, including standard CRUD operations (create-read-update-delete).

You can define other queries as needed by simply declaring their method signature. In this case, you add `findByFirstName`, which essentially seeks documents of type `Customer` and finds the one that matches on `firstName`.

You also have `findByLastName` to find a list of people by last name.

In a typical Java application, you write a class that implements `CustomerRepository` and craft the queries yourself. What makes Spring Data MongoDB so useful is the fact that you don't have to create this implementation. Spring Data MongoDB creates it on the fly when you run the application.

Let's wire this up and see what it looks like!

== Create an Application class
Here you create an Application class with all the components.

`src/main/java/io/pivotal/Application.java`
[source,java]
----
include::complete/src/main/java/io/pivotal/Application.java[]
----

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/spring-boot-application.adoc[]

Spring Boot will handle those repositories automatically as long as they are included
in the same package (or a sub-package) of your `@SpringBootApplication` class. For more control over the
registration process, you can use the `@EnableMongoRepositories` annotation.

NOTE: By default, `@EnableMongoRepositories` will scan the current package for any interfaces that extend one of Spring Data's repository interfaces. Use it's `basePackageClasses=MyRepository.class` to safely tell Spring Data MongoDB to scan a different root package by type if your project layout has multiple projects and its not finding your repositories.

Spring Data MongoDB uses the `MongoTemplate` to execute the queries behind your `find*` methods. You can
use the template yourself for more complex queries, but this guide doesn't cover that.

`Application` includes a `main()` method that autowires an instance of `CustomerRepository`: Spring Data
MongoDB dynamically creates a proxy and injects it there. We use the `CustomerRepository` through a few
tests. First, it saves a handful of `Customer` objects, demonstrating the `save()` method and setting
up some data to work with. Next, it calls `findAll()` to fetch all `Customer` objects from the database.
Then it calls `findByFirstName()` to fetch a single `Customer` by her first name. Finally, it calls
`findByLastName()` to find all customers whose last name is "Smith".

NOTE: Spring Boot by default attempts to connect to a locally hosted instance of MongoDB. Read the http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-mongodb[reference docs] for details on pointing your app to an instance of MongoDB hosted elsewhere.

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_mainhead.adoc[]
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_with_both.adoc[]

As our `Application` implements `CommandLineRunner`, the `run` method is invoked automatically when boot
starts. You should see something like this (with other stuff like queries as well):
....
== Customers found with findAll():
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']

== Customer found with findByFirstName('Alice'):
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
== Customers found with findByLastName('Smith'):
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']
....

== Connecting to an external Mongo instance

If you wanted to connect to a Mongo instance on Azure, you could add (though not recommended) an `application-cloud.yml` file to `src/main/resources` containing, e.g.,

```
spring:
data:
mongodb:
uri: mongodb://{username}:{password}@{host}.mlab.com:46267/{database-name}

management:
cloudfoundry:
enabled: true
skip-ssl-validation: true
```

Host a free 500mb instance of Mongo available on AWS, GCP or Azure @ https://mlab.com!

== Summary
Congratulations! You set up a MongoDB server and wrote a simple application that uses Spring Data MongoDB to save objects to and fetch them from a database -- all without writing a concrete repository implementation.

NOTE: If you're interesting in exposing MongoDB repositories with a hypermedia-based RESTful front end with little effort, you might want to read link:/guides/gs/accessing-mongodb-data-rest[Accessing MongoDB Data with REST].

== See Also

The following guides may also be helpful:

* https://spring.io/guides/gs/accessing-data-jpa/[Accessing Data with JPA]
* https://spring.io/guides/gs/accessing-data-gemfire/[Accessing Data with Gemfire]
* https://spring.io/guides/gs/accessing-data-mysql/[Accessing data with MySQL]
* https://spring.io/guides/gs/accessing-data-neo4j/[Accessing Data with Neo4j]

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/footer.adoc[]