,

Recently we’ve seen a rise in popularity of NoSQL databases. MongoDB has rapidly gained popularity in the enterprise and the Spring community.

While developing and testing Spring Boot applications with MongoDB as the data store, it is common to use the lightweight Embedded MongoDB rather than running a full-fledged server. As the embedded MongoDB runs in memory, it is blazing fast and will save you lot of time both during development and running your tests, in your development machine or a CI server.

I have covered setting up MongoDB in a Spring Boot application here.

In this post, I’ll discuss how to use embedded MongoDB in a Spring Boot application.

I posted a video here that explains the Spring Boot application that I’ll use in this post.

The Maven POM

Embedded MongoDB downloads and fires-up a real MongoDB instance. You get the benefit of talking to an instance loaded in memory with the same capabilities as your production environment. The Maven POM dependency to include Embedded MongoDB is this:

You also need to include the embedmongo-spring dependency that provides Spring Factory Bean for Embedded MongoDB, like this.

Finally, with this spring-boot-starter-data-mongodb dependency pulled in, you should be all set to use embedded MongoDB in your Spring Boot app.

The complete pom.xml is this.

pom.xml

The MongoDB Config

You need to provide a MongoTemplate bean to SpringBoot for your application to interact with the embedded MongoDB instance. You typically use a @Configuration class, like this.

MongoConfig.java

In this MongoConfig class, EmbeddedMongoFactoryBean is a FactoryBean for Embedded MongoDB that runs MongoDB as a managed process and exposes preconfigured instance of MongoClient.

This is all you need to do to start using Embedded MongoDB in a Spring Boot application.

Note: By default your application will connect to the test database. For a different database, set the spring.data.mongodb.database property in your application.properties configuration file.

You can download the source code from git here.

0
Share
,

Spring Data project provides integration for most of the popular databases around. I have already written few posts to configure Spring Boot to use Oracle, MySQL, and PostgreSQL – all RDBMS widely used in the enterprise.

Recently we’ve seen a rise in popularity of NoSQL databases.  MongoDB has rapidly gained popularity in the enterprise and the Spring community.

In this post, I’ll discuss how to use MongoDB with a Spring Boot application.

NoSQL and MongoDB

NoSQL storage is a vast domain with a plethora of solutions and patterns. Even the term NoSQL have multiple meanings. Originally it stood for “Non SQL”, but gradually with the adoption of Polyglot Persistence which Martin Flower beautifully describes here,

NoSQL is now commonly referred as “Not Only SQL”.

MongoDB is a leading document-based NoSQL database. MongoDB uses JSON documents to store records. Internally, MongoDB represents JSON documents in binary-encoded format called BSON. One feature worth mentioning about MongoDB is it’s dynamic schema. You can insert data without a pre-defined schema – a thing not possible with traditional relational databases.

In today’s competitive business environment where Agile practices are embraced, having a dynamic schema gives you a high degree of flexibility. A great place to learn more about MongoDB is here.

For this post, I’m using MongoDB installed locally on my laptop. You have several options for running MongoDB.

You have several options for running MongoDB. Refer to the MongoDB guide for an explanation on how to install and start up a MongoDB instance.

MongoDB Dependencies

Spring Data for MongoDB is part of the umbrella Spring Data project. With Spring Data for MongoDB, you get a familiar and consistent Spring-based programming model to work with for MongoDB while retaining MongoDB store-specific features and capabilities.

To use MongoDB in a Spring Boot project, we need to add the Spring Data MongoDB starter dependency, spring-boot-starter-data-mongodb . The Maven POM is this.

pom.xml

Notice that we haven’t included Spring data JPA – The Spring Data MongoDB starter dependency brings in the required infrastructure, the MongoDB driver, and few other dependencies to the project.

MongoDB Dependencies with Spring Boot starter

Data Class

Both Spring Data JPA and Spring Data MongoDB share the same common infrastructure. I have already written a post to use Spring Data JPA in a Spring Boot Web application.

Here we need to write a Mongo data class rather than a JPA @Entity. A Mongo data class instance maps to a document stored in a collection.

Note: You can relate a collection of MongoDB to an RDBMS table, and a document to a table row.

Let’s write a User data class.

User.java

We have created User as a plain Java object. The @Document annotation in Line 6 specifies a users collection. This tells Spring Data MongoDB to store a User document to the users collection. This collection will be created if it doesn’t exist. The @Document annotation is optional, and if we don’t use one, the collection will be named with the class name.

All documents in MongDB have an _id field as the primary key. The id field annotated with @Id in Line 8 maps to the MongoDB document’s _id. It’s not mandatory to use the @Id annotation if the primary key field is named id . However, many still use the annotation for readability. Some consider it a best practice to use the Id annotation, even when its not required.

The remaining name and age field will be treated as properties of the MongoDB document.

Mongo Repository

Spring Data Mongo provides Mongo Repository, similar to CRUD Repository of Spring Data JPA. In fact, the MongoRepository interface extends CrudRepository to manage data objects for most common operations, such as saving a document, updating it, deleting it, or finding it by id.

You only need to define the repository interface. Spring Data MongoDB will automatically provide the required implementations.

Here is the Mongo repository:

UserMongoRepository.java

That’s all we need to set to use MongoDB with Spring Boot.

Unit Testing

Lets write some test code for our setup.

UserMongoRepositoryTest.java

For the test, I have used JUnit. To learn more about JUnit, refer my series on JUnit Testing.

Here is the result of the JUnit test.
JUnit Test Result for MongoDB

Configuration Properties

If you are wondering about MongoDB configurations, for this simple application we relied on the defaults. Spring Data MongoDB intelligently picks up the defaults, such as localhost for the host, 27017 for the default MongoDB port, and test for the default MongoDB database to connect. For other values or for advance configurations, you can use the application.properties or application.yml configuration files.

The MongoDB configurations that Spring Boot supports are as follows:

Conclusion

Spring Boot makes it very easy to get a Spring application talking to a Mongo database. By default, Spring Boot is configured to look for the Mongo database on the local host. When you’re ready to deploy, you just need to override a handful of default properties for your particular MongoDB installation.

1
Share