Springboot MongoDB Repository – Code Example

0

This blog represents code required to create a Spring boot application that uses Spring Data MongoRepository interface to connect with MongoDB database.

Step 1: Create a Springboot Maven project

Create a new Spring Starter Project using Eclipse IDE. This would create a class annotated with @SpringBootAnnotation.

Step 2: Include Spring Data Mongo support in pom.xml

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

Step 3: Configure Mongoclient for database connectivity

Create a Configuration class which is used to instantiate a MongoClient for connecting with MongoDB database.

package com.vflux.demo.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

@Configuration
@EnableMongoRepositories(basePackages = "com.vflux.demo.repository")
@PropertySource("classpath:application.properties")
public class MongoConfig extends AbstractMongoConfiguration {

    @Value("${mongodb.name}")
    private String  dbName;

    @Value("${mongodb.authDB}")
    private String  authDB;

    @Value("${mongodb.host}")
    private String  host;

    @Value("${mongodb.port}")
    private String port;

    @Value("${mongodb.username}")
    private String  username;

    @Value("${mongodb.password}")
    private String  password;


    @Override
    protected String getDatabaseName() {
        return this.dbName;
    }

    @Override
    public Mongo mongo() throws Exception {                
        List<ServerAddress> seeds = new ArrayList<ServerAddress>();
        seeds.add( new ServerAddress(this.host, Integer.parseInt(this.port.trim())) );
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        MongoCredential userCredential = MongoCredential.createCredential(this.username, this.authDB, this.password.toCharArray());
        credentials.add(userCredential);
        return new MongoClient( seeds, credentials );
    }

    @Override
    protected String getMappingBasePackage() {
        return "com.vflux.demo";
    }

}

Step 3: Define MongoDB details in application.properties

# MongoDB properties
mongodb.name=vitalflux
mongodb.host=localhost
mongodb.port=27017
mongodb.username=ajitesh
mongodb.password=vitalflux
mongodb.authDB=vitalflux

Step 4: Invoke MongoRepository instance

Place following code in SpringBootAnnotation class for invoking MongoRepository instance (UserDAO in the code given below). In ideal scenario, you would want to invoke this DAO class from a service class.

package com.vflux.demo;

import java.util.concurrent.ThreadLocalRandom;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.vflux.demo.domain.User;
import com.vflux.demo.repository.UserDAO;

@SpringBootApplication
public class DemoAppApplication {

    private static UserDAO userDAO;

    @Autowired
    public void setPersonCountDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }


    public static void main(String[] args) {
        SpringApplication.run(DemoAppApplication.class, args);
        createUser();
    }

    private static void createUser() {
        User user = new User();
        user.setFirstname("Calvin");
        user.setLastname("Hobbes");
        user.setAge(20);
        user.setLocation("Hyderabad");
        userDAO.insert(user);
    }


}

Step 5: Create a UserDAO interface

package com.vflux.demo.repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.vflux.demo.domain.User;

public interface UserDAO extends MongoRepository<User, String> {
    User insert(User user);
}

Step 6: Create a Document class

In the above code, a User class is used. The User class can represent a collection in MongoDB with name as user.

package com.vflux.demo.domain;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class User {

    @Id
    private String id;
    private String firstname;
    private String middlename;
    private String lastname;
    private int age;
    private String location;
    private String role;

    public User() {}

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getMiddlename() {
        return middlename;
    }

    public void setMiddlename(String middlename) {
        this.middlename = middlename;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}
Ajitesh Kumar

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, .NET, C/C++, mobile programming languages etc and, computing fundamentals such as application security, cloud computing, API, mobile apps, google glass, big data etc.Recently, he has been digging deep into the field of data science and machine learning.

Follow him on Twitter and Google+.
Ajitesh Kumar

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.