Spring Boot

Spring Boot and MongoDB in REST Application

Hello friends !!! In this tutorial we are going to discuss about using NoSQL database MongoDB with Spring Boot Application. Here I will make a Spring Boot REST Application which provides REST APIs for make booking, read booking, update booking and delete booking.
Spring Boot with NoSQL
Spring Data provides additional projects that help you access a variety of NoSQL technologies including MongoDB, Neo4J, Elasticsearch, Solr, Redis, Gemfire, Couchbase and Cassandra. Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Elasticsearch, Solr and Cassandra.
NoSQL MongoDB
NoSQL is a non-relational database management system, different from traditional relational database management systems in some significant ways. MongoDb is a Open Source database written in C++. It can be used to store data for very high performance applications (for example Foursquare is using it in production).
MongoDB stores data as documents. So it is a document oriented database.

MongoDB with Spring Boot & Spring Data
Spring Boot and Spring Data make it even easier to get a simple application up and running. With a little bit of configuration and minimal code, you can quickly create and deploy a MongoDB-based application. Spring Boot offers several conveniences for working with MongoDB, including the spring-boot-starter-data-mongodbStarter’.
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

You can set spring.data.mongodb.uri property to change the URL and configure additional settings such as the replica set:

spring.data.mongodb.uri=mongodb://user:secret@mongo1.example.com:12345,mongo2.example.com:23456/test
Spring Data includes repository support for MongoDB. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names.
MongoDB with Spring Boot Application
Let’s start to develop simple REST API project for ticket booking with Spring Boot and MongoDB. First, make sure you have installed MongoDB and are able to run it. Second make sure you have installed Maven 4.X.
Next, we are going to create a Spring Boot web application. You can do so by using the web-based wizard here. In the dependencies section, you’ll want to select: Web, and MongoDB.
Import into STS IDE
After downloading from the web interface now unzip the project “SpringBootMongoDB” and import in the STS IDE or Eclipse as Maven project. As below project structure look like. Now that the basic maven based Spring boot is ready.


Let’s discuss about the application files

Configuration file application.properties

spring.data.mongodb.database=dojdb
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
There are no need add any configuration to this file spring boot provide auto-configuration for mongodb when added starter for mongodb to application maven file. If you want to change mongo configuration default you can add above properties to the application.properties file.
Here we are telling Spring Data the host and port of our Mongo instance. We also give it a database name, and if the database doesn’t already exist it will be created for us.
Maven Configuration pom.xml

Following dependencies to be added with maven file

<?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>com.dineshonjava.sbmdb</groupId>
 <artifactId>SpringBootMongoDB</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringBootMongoDB</name>
 <description>SpringBootMongoDB project for Spring Boot with MongoDB providing APIs</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.0.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

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

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>


</project>

Let me create a model class to hold Booking details retrieved from DB.
Now, we need to model our documents. Let’s call ours ‘Booking’ and give it a make, model, and description. Here is our Java class to accomplish this:
Booking.java
/**
 * 
 */
package com.dineshonjava.sbmdb.models;

import java.util.Date;

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

/**
 * @author Dinesh.Rajput
 *
 */
@Document
public class Booking{

 @Id
 String id;
 String psngrName;
 String departure;
 String destination;
 Date travelDate;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getPsngrName() {
  return psngrName;
 }

 public void setPsngrName(String psngrName) {
  this.psngrName = psngrName;
 }

 public String getDeparture() {
  return departure;
 }

 public void setDeparture(String departure) {
  this.departure = departure;
 }

 public String getDestination() {
  return destination;
 }

 public void setDestination(String destination) {
  this.destination = destination;
 }

 public Date getTravelDate() {
  return travelDate;
 }

 public void setTravelDate(Date travelDate) {
  this.travelDate = travelDate;
 }
 
 
}

@Id- id provided by Mongo for a document.
@Document- provides a collection name.
Lets add Repository class to interact with the DB
BookingRepository.java
A Repository is a way to manage data objects in Spring Data. For most common methods – like saving a document, updating it, deleting it, or finding it by id – Spring Data will automatically implement the necessary logic.
package com.dineshonjava.sbmdb.models;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public interface BookingRepository extends MongoRepository {
 
 /**
    * This method will find an Boooking instance in the database by its departure.
    * Note that this method is not implemented and its working code will be
    * automatically generated from its signature by Spring Data JPA.
    */
   public Booking findByDeparture(String departure);
}

The MongoRepository provides basic CRUD operation methods and also an API to find all documents in the collection.
Implementing RestController for Create and Get Details API
BookingController.java
/**
 * 
 */
package com.dineshonjava.sbmdb.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dineshonjava.sbmdb.models.Booking;
import com.dineshonjava.sbmdb.models.BookingRepository;

/**
 * @author Dinesh.Rajput
 *
 */
@RestController
@RequestMapping("/booking")
public class BookingController {
 
 @Autowired
 BookingRepository bookingRepository;
 /**
  * GET /create  --> Create a new booking and save it in the database.
  */
 @RequestMapping("/create")
 public Map<String, Object> create(Booking booking) {
  booking.setTravelDate(new Date());
  booking = bookingRepository.save(booking);
  Map<String, Object> dataMap = new HashMap<String, Object>();
  dataMap.put("message", "Booking created successfully");
  dataMap.put("status", "1");
  dataMap.put("booking", booking);
     return dataMap;
 }
 
 /**
  * GET /read  --> Read a booking by booking id from the database.
  */
 @RequestMapping("/read")
 public Map<String, Object> read(@RequestParam String bookingId) {
  Booking booking = bookingRepository.findOne(bookingId);
  Map<String, Object> dataMap = new HashMap<String, Object>();
  dataMap.put("message", "Booking found successfully");
  dataMap.put("status", "1");
  dataMap.put("booking", booking);
     return dataMap;
 }
 
 /**
  * GET /update  --> Update a booking record and save it in the database.
  */
 @RequestMapping("/update")
 public Map<String, Object> update(@RequestParam String bookingId, @RequestParam String psngrName) {
  Booking booking = bookingRepository.findOne(bookingId);
  booking.setPsngrName(psngrName);
  booking = bookingRepository.save(booking);
  Map<String, Object> dataMap = new HashMap<String, Object>();
  dataMap.put("message", "Booking updated successfully");
  dataMap.put("status", "1");
  dataMap.put("booking", booking);
     return dataMap;
 }
 
 /**
  * GET /delete  --> Delete a booking from the database.
  */
 @RequestMapping("/delete")
 public Map<String, Object> delete(@RequestParam String bookingId) {
  bookingRepository.delete(bookingId);
  Map<String, Object> dataMap = new HashMap<String, Object>();
  dataMap.put("message", "Booking deleted successfully");
  dataMap.put("status", "1");
     return dataMap;
 }
 
 /**
  * GET /read  --> Read all booking from the database.
  */
 @RequestMapping("/read-all")
 public Map<String, Object> readAll() {
  List<Booking> bookings = bookingRepository.findAll();
  Map<String, Object> dataMap = new HashMap<String, Object>();
  dataMap.put("message", "Booking found successfully");
  dataMap.put("totalBooking", bookings.size());
  dataMap.put("status", "1");
  dataMap.put("bookings", bookings);
     return dataMap;
 }
}
Lets run the application by either using Spring Boot maven plug-in i.e. by running mvn spring-boot:run or by running the main class SpringBootMongoDbApplication.java from Eclipse or your IDE.
package com.dineshonjava.sbmdb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootMongoDbApplication {

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

Creating New Record:
/booking/create?psngrName=Dinesh&departure=Noida&destination=Pune create a new booking with an auto-generated.

For Example:
http://localhost:8080/booking/create?psngrName=Vinesh&destination=Delhi&departure=Farrukhabad
{
• booking:
{
o id: “57abe8d42ca52424e8e88027”,
o psngrName: “Vinesh”,
o departure: “Farrukhabad”,
o destination: “Delhi”,
o travelDate: 1470884052977
},
• message: “Booking created successfully”,
• status: “1”
}

Reading a Record:
/booking/read?id=[bookingId]: Read the booking with the passed bookingId.
For Example:
http://localhost:8080/booking/read?bookingId=57abe8932ca52424e8e88024
{
• booking:
{
o id: “57abe8932ca52424e8e88024”,
o psngrName: “Arnav”,
o departure: “Pune”,
o destination: “USA”,
o travelDate: 1470883987113
},
• message: “Booking found successfully”,
• status: “1”
}

Updating a Record:
/booking/update?bookingId=[bookingId]&psngrName=Sweety: Update the booking for a given booking id.
For Example:
http://localhost:8080/booking/update?bookingId=57abe8a72ca52424e8e88025&psngrName=Anamika
{
• booking:
{
o id: “57abe8a72ca52424e8e88025”,
o psngrName: “Anamika”,
o departure: “Noida”,
o destination: “USA”,
o travelDate: 1470884007369
},
• message: “Booking updated successfully”,
• status: “1”
}

Read All Records
http://localhost:8080/booking/read-all
{
• totalBooking: 5,
• message: “Booking found successfully”,
• bookings:
[
o {
 id: “57abe8322ca52424e8e88023”,
 psngrName: “Dinesh”,
 departure: “Noida”,
 destination: “Pune”,
 travelDate: 1470883890814
},
o {
 id: “57abe8932ca52424e8e88024”,
 psngrName: “Arnav”,
 departure: “Pune”,
 destination: “USA”,
 travelDate: 1470883987113
},
o {
 id: “57abe8a72ca52424e8e88025”,
 psngrName: “Sweety”,
 departure: “Noida”,
 destination: “USA”,
 travelDate: 1470884007369
},
o {
 id: “57abe8bf2ca52424e8e88026”,
 psngrName: “Adesh”,
 departure: “Kannauj”,
 destination: “Noida”,
 travelDate: 1470884031444
},
o {
 id: “57abe8d42ca52424e8e88027”,
 psngrName: “Vinesh”,
 departure: “Farrukhabad”,
 destination: “Delhi”,
 travelDate: 1470884052977
}
],
• status: “1”
}

Deleting a Record:
/booking/delete? bookingId=[bookingId]: Delete a booking for given booking id.

For Example:
http://localhost:8080/booking/delete?bookingId=57ac0d681ff9b3117caf7c85
{
• message: “Booking deleted successfully”,
• status: “1”
}
Summary
In this chapter I have explained how to use Spring Data MongoDB and Spring Boot frameworks. Great you set up a MongoDB server and wrote a simple application that uses Spring Data MongoDB to save objects to and fetch them from a database — all without writing a concrete repository implementation.

Whole Source code here

Happy Spring Boot Learning!!!

 

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago