Categories: JavaMongoDBNoSQL

Springboot MongoDB Repository – Code Example

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

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

Recent Posts

Agentic Reasoning Design Patterns in AI: Examples

In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…

1 month ago

LLMs for Adaptive Learning & Personalized Education

Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…

2 months ago

Sparse Mixture of Experts (MoE) Models: Examples

With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…

2 months ago

Anxiety Disorder Detection & Machine Learning Techniques

Anxiety is a common mental health condition that affects millions of people around the world.…

2 months ago

Confounder Features & Machine Learning Models: Examples

In machine learning, confounder features or variables can significantly affect the accuracy and validity of…

2 months ago

Credit Card Fraud Detection & Machine Learning

Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…

2 months ago