Spring Boot MongoDB+MLAB

Spring Boot MongoDB and MLAB:- 

This article demonstrates how to use Spring Boot MongoDB and MLAB.The Whole advantage of using Spring boot is to auto configuration. Spring boot helps us to save a lot of time during our development. We are going to write simple application to do some basic operations using Spring Boot MongoDB.We are going to use cloud hosted mongo service mlab. This is the one of the best and free database platform as a service for using mongo db  .



Configure MongDb on MLAB:-

Step 1:-Vist the website mlab and signup , once you are successfully signed up you will see the following screen.

Spring Boot MongoDB +MLAB

Step2:- Click on Create button.On the next screen you need to Choose the free plan and move to the next screen.Enter the database name as name of your choice.

Spring Boot MongoDB +MLAB

Step 3 :- Click on the row above you will get your mongo database details.

Spring Boot MongoDB +MLAB

Step 4:- Now lets create a mongo user.We can’t leave our database unauthenticated.Click On Add Database User and add user details and hit Create. Store the user and password at some safe place.

Spring Boot MongoDB +MLAB

So now We have got our mongodb URL, replace username and password with the one you created earlier:-

mongodb://<USER>:<PASSSWORD>@ds261828.mlab.com:61828/springdb

Create A Spring Boot MongoDB Application :-

I am Covering the Spring Boot Mongo DB in short, as i am planning to cover REST Services using Spring BootMongoDB as well.There I will explain each and every component in a better way .

Project Structure:-

Use https://start.spring.io/ to create a Spring boot MongoDB Project .

Project Dependencies:

You can use start.spring.io to create a project with dependency as MongoDB.

pom.xml:-

<?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.frugals</groupId>
	<artifactId>Sprimngjpa</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Sprimngjpa</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.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>

Configure Application Properties File:-

application.properties:-

spring.data.mongodb.uri=mongodb://<USERNAME>:<PASSWORD>@ds261828.mlab.com:61828/springdb

Create a User Database Bean To be Stored In MongoDB :-

User.java:-

In Spring Boot MongoDB,If we dont specify collection name it will take classname as collection name by default.

package com.frugals.Sprimngjpa.entity;

/**
 * Created by Sanju on 08-Mar-18.
 */
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Document(collection = "users")

public class User {
    @Id
    int id;
    String name;
    String age;

    public User(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Create Repository To Access Collections in Spring Boot MongoDB :-

There is no concept of table when it comes to mongodb or any no sql database.Lets create a simple repository that access data from mongodb .

public interface UserRepository extends MongoRepository<User,Integer> {
    public List<User> findByName(String name);

}

Save and Retrieve Data from Spring Boot Mongo DB:-

MainApplication.java

package com.frugals.Sprimngjpa;

import com.frugals.Sprimngjpa.entity.User;
import com.frugals.Sprimngjpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.List;

@SpringBootApplication
public class SprimngjpaApplication {

	@Autowired
	UserRepository userRepository;

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


	@Bean
	CommandLineRunner runner(){
		return args -> {

			System.out.print("<<<<<<<<<<<<<Cleaning MongoDatabase>>>>>>>>>>>>>>");
			userRepository.deleteAll();

			for(int i=0;i<5;i++){
				User user=	userRepository.save(new User(i,"Test",String.valueOf(i+12)));

				System.out.println("<<<<<<<<<<<<<Adding User >>>>>>>>>>>>>>");
				System.out.println("***"+user.toString()+"***");
			}

			System.out.println("<<<<<<<<<<<<<Get All  User >>>>>>>>>>>>>>");
			List<User> alluser=userRepository.findAll();
			alluser.forEach(item -> System.out.println(item));

			alluser.clear();

			System.out.println("<<<<<<<<<<<<<Find User By Name >>>>>>>>>>>>>>");
		    alluser=userRepository.findByName("Test");
			alluser.forEach(item -> System.out.println(item));

			System.out.println("Executed");

		};
	}
}

Output:- 

Run the command mvn spring-boot:run

<<<<<<<<<<<<<Adding User >>>>>>>>>>>>>>
***User{id=0, name='Test', age='12'}***
<<<<<<<<<<<<<Adding User >>>>>>>>>>>>>>
***User{id=1, name='Test', age='13'}***
<<<<<<<<<<<<<Adding User >>>>>>>>>>>>>>
***User{id=2, name='Test', age='14'}***
<<<<<<<<<<<<<Adding User >>>>>>>>>>>>>>
***User{id=3, name='Test', age='15'}***
<<<<<<<<<<<<<Adding User >>>>>>>>>>>>>>
***User{id=4, name='Test', age='16'}***
<<<<<<<<<<<<<Get All  User >>>>>>>>>>>>>>
User{id=0, name='Test', age='12'}
User{id=1, name='Test', age='13'}
User{id=2, name='Test', age='14'}
User{id=3, name='Test', age='15'}
User{id=4, name='Test', age='16'}
<<<<<<<<<<<<<Find User By Name >>>>>>>>>>>>>>
User{id=0, name='Test', age='12'}
User{id=1, name='Test', age='13'}
User{id=2, name='Test', age='14'}
User{id=3, name='Test', age='15'}
User{id=4, name='Test', age='16'}
Executed

MLab Output:-

Spring Boot MongoDB +MLAB
[sociallocker id=”1183″]

[/sociallocker]