Setting up a Spring Boot application with MongoDB

Spring Boot provides excellent support for applications accessing MongoDB as a database. The following preparations are necessary to create our own application using Spring Data MongoDB.

Configuration

As a document-oriented database, MongoDB will not be connected to our application using Hibernate as an ORM layer. Instead, we add spring-boot-starter-data-mongodb as a dependency to our app, providing a similar approach to accessing MongoDB using POJOs and repositories.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Required Maven dependency

With this dependency in place, we can extend our application.yml or application.properties with an uri. If the database does not exist yet, MongoDB will create it automatically. With setting auto-index-creation to true, unique indexes are added during startup of our app if they are annotated in our documents with @Indexed(unique = true).

spring.data.mongodb.uri=mongodb\://localhost\:27017/mongo
spring.data.mongodb.auto-index-creation=true

Only the uri is required for a successful database connection

In our configuration class, @EnableMongoRepositories should be set. This will search for classes in the specified package that extend MongoRepository - an example of this will be given in a moment. By providing the ValidatingMongoEventListener all documents are validated before persisting, and we can extend their fields with javax.validation constraints like @NotNull.

@Configuration
@EnableMongoRepositories("io.bootify.mongo.repos")
public class MongoConfig {

    @Bean
    public ValidatingMongoEventListener validatingMongoEventListener(
            final LocalValidatorFactoryBean factory) {
        return new ValidatingMongoEventListener(factory);
    }

}

First version of our config

Furthermore we want to enable transaction support for our application. This allows us, for example, to mark the methods of our services as @Transactional. Please note that this requires our MongoDB instance to be initialized as replica set to support this feature.

@Bean
public MongoTransactionManager transactionManager(final MongoDatabaseFactory databaseFactory) {
    return new MongoTransactionManager(databaseFactory);
}

Adding transaction support to our config

Example Document and Repository

With these preparations, we can already define a simple document and its associated repository. For our example we use a primary key of type String, which is automatically generated by MongoDB as ObjectID if we do not provide it. To use our own sequence as a primary key, there are instructions on how to do so in this article.

@Document
public class Customer {

    @Id
    private String id;

    @Size(max = 255)
    private String firstName;

    @Size(max = 255)
    private String lastName;

    @Indexed(unique = true)
    @NotNull
    @Size(max = 255)
    private String email;

}

Our first POJO, mapped to a collection named "customer"

We add our repository by extending MongoRepository. It works in the same way as known from Spring Data and can be extended with custom queries.

public interface CustomerRepository extends MongoRepository<Customer, String> {

    Customer findByEmail(String email);

}

Basic Repository for MongoDB

With this, all preparations are done to connect our Spring Boot application with MongoDB. In Bootify's Free plan, we can generate the application with our custom database schema without registration. The runnable source code of our application is then directly available for download.

» Start Project on Bootify.io