1. Overview

In this article, We will learn how to develop Spring boot Rest Service with MongoDB. MongoDB is a popular NoSQL database and widely used database for newly started applications. In this example, We have used Spring Data to perform the operations with the MongoDB database.

We have explained here CRUD (Create, Read, Update and Delete) operations with JSON Rest Service and used MongoDB database.

NOTE: Make sure that MongoDB server is running, By default it will run on 27017 port.

2.  Spring boot Rest Service with MongoDB Example

Spring boot Rest Service with MongoDB Example

Spring boot Rest Service with MongoDB Example

2.1 pom.xml

  • spring-boot-starter-data-mongodb for MongoDB
  • spring-boot-starter-web for Spring web and Rest Service
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring-boot-example</groupId>
    <artifactId>spring-boot-hibernate-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <description>Spring boot Rest Service with MongoDB Example</description>
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>

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

    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.2 application.properties

  • spring.data.mongodb.host indicates MongoDB host or IP
  • spring.data.mongodb.port indicates MongoDB port
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017

2.3 SpringBootConfig

  • @EnableMongoRepositories : It will enable MongoDB repository and we have provided based package here so it will be considered as a repository based package.
  • @SpringBootApplication: Indicate as Spring boot application
package com.javadeveloperzone;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * Created by Java Developer Zone on 19-07-2017.
 */

@SpringBootApplication
@ComponentScan
@EnableMongoRepositories("com.javadeveloperzone.repository")
// Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }
}

2.4 EmployeeController

Here we have created RestController which will accept incoming HTTP request,

  • @RequestMapping(value = "save",method = RequestMethod.POST) for POST method, It will accept form parameters and save data to MongoDB database. We can directly use @GetMapping like @GetMapping(value = "save")
  • @RequestMapping(value = "list",method = RequestMethod.GET) to list all the Employee
  • @RequestMapping(value = "delete", method = RequestMethod.DELETE) to delete particular Employee
package com.javadeveloperzone.controller;

import com.javadeveloperzone.model.Employee;
import com.javadeveloperzone.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@RestController     // for rest response
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    // to add new employee
    @RequestMapping(value = "save",method = RequestMethod.POST)     // or user @GetMapping
    public Employee save(Employee employee){
        return employeeService.save(employee);
    }

    // to update employee
    @RequestMapping(value = "update",method = RequestMethod.POST)     // or user @GetMapping
    public Employee update(Employee employee){
        return employeeService.update(employee);
    }

    // list of all employee
    @RequestMapping(value = "list",method = RequestMethod.GET)   // or use @GetMapping
    public java.util.List<Employee> listEmployee() {
        return employeeService.findAll();
    }

    // delete specific employee using employee id
    @RequestMapping(value = "delete", method = RequestMethod.DELETE)        // or use @DeleteMapping
    public void delete(@RequestParam("id")String id){
         employeeService.delete(id);
    }
}

2.5 EmployeeService

  • It normal interface which contains CRUD methods.
package com.javadeveloperzone.service;

import com.javadeveloperzone.model.Employee;

import java.util.List;

/**
 * Created by JavaDeveloperZone on 04-04-2018.
 */

public interface EmployeeService {
    List<Employee> findAll();
    Employee save(Employee employee);
    void delete(String employeeId);
    Employee update(Employee employee);
}

2.6 EmployeeServiceImpl

  • Service Implementation where actually business logic has been written. @Service indicate service layer.
  • We have Autowire EmployeeRepository using that we can communicate with MongoDB database.
package com.javadeveloperzone.service;

import com.javadeveloperzone.repository.EmployeeRepository;
import com.javadeveloperzone.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Java Developer Zone on 04-04-2018.
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public List<Employee> findAll() {
        return employeeRepository.findAll();
    }


    @Override
    public void delete(String employeeId) {
        employeeRepository.delete(employeeRepository.findOne(employeeId));
    }

    @Override
    public Employee save(Employee employee) {
        return employeeRepository.save(employee);
    }

    @Override
    public Employee update(Employee employee) {
        return employeeRepository.save(employee);
    }
}

2.7 EmployeeRepository

  • Here, @Repository indicate repository which will communicate with MongoDB database and extands MongoRepository interface which contains basic methods to fetch data from MongoDB
  • Using @Query we can write a custom query which is supported by MongoDB

Here we just define method name, Spring data will automcatilly create query using method name. Here is more details for the same.

package com.javadeveloperzone.repository;

import com.javadeveloperzone.model.Employee;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;


/**
 * Created by Java Developer Zone on 03-08-2017.
 */
@Repository
public interface EmployeeRepository extends MongoRepository<Employee,String> {

    @Override
    List<Employee> findAll();           // find all Employee

    @Query(value = "{ 'employeeName' : ?0 }")
    List<Employee> findByEmployeeName(String name);       // find employee by name

    Employee findByEmployeeId(String id);           // find

    @Override
    void delete(String s);              // delete by ID
}

2.8 Employee

  • @Document indicates the MongoDB document.
  • @Id indicate the primary key, It will not allow duplicate value. When the data type is String at that time it will automatically generate random Id.
package com.javadeveloperzone.model;

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

/**
 * Created by Java Developer Zone on 03-08-2017.
 */
@Document(collection = "Employee")
public class Employee {

    @Id                                                     // primary key
    private String employeeId;

    private String employeeName;

    private String employeeRole;

    public String getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeRole() {
        return employeeRole;
    }

    public void setEmployeeRole(String employeeRole) {
        this.employeeRole = employeeRole;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
}

2.9 Output

Let’s run and check spring boot application and perform different operations:

1. Spring boot MongoDB – Save Operation

Spring boot MongoDB - Save Operation

Spring boot MongoDB – Save Operation

2. Spring boot MongoDB – List Operation

Spring boot MongoDB - List Operation

Spring boot MongoDB – List Operation

3. Spring boot MongoDB – Delete operation

Spring boot MongoDB - Delete Operation

Spring boot MongoDB – Delete Operation

3. Conclusion

We have learned about the way to develop JSON Rest Service with MongoDB database and also learned insert, update and delete operations with MongoDB in the content of Spring boot application.

4. References

5. Source Code

spring-boot-jpa-mongodb-rest-example (44 KB)

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *