Connecting Java to MongoDB

Connecting Java to MongoDB

This article teaches you how to connect Java to MongoDB and how to do CRUD operations. The prerequisite is to read my previous articles related to basic of MongoDB and authentication of MongoDB. To understand this please go through the steps are given below. I used IntelliJ idea to develop the project.

This is the structure of my application please follow this.

This is the pom file. Please download all dependencies according to the YouTube video.

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.8.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.java</groupId>
	<artifactId>mongo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>mongo</name>
	<description>Mongo Java Project</description>

	<properties>
		<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>

Firstly, you have to add the below property. This is the application.properties file

spring.data.mongodb.uri=mongodb://myuser:xyz123@localhost:27017/testMongo

Secondly you have to create a model class

package com.java.mongo.model;

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

@Document
public class Users {
    @Id
    private String id;
    private String name;
    private int age;
    private String gender;
    private String country;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

Then create a repository interface

package com.java.mongo.dao;

import com.java.mongo.model.Users;

import java.util.List;

public interface userRepository {
    Users save(Users users);
    boolean update(Users users);
    boolean remove(String id);
    List<Users> search();
}

After that implementation of the repository interface

package com.java.mongo.dao;

import com.java.mongo.model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class userRepositoryImpl implements userRepository{

    @Autowired private MongoTemplate mongoTemplate;

    @Override
    public Users save(Users users) {
        return mongoTemplate.save(users);
    }

    @Override
    public boolean update(Users users) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(users.getId()));

        Update update = new Update();
        update.set("name", users.getName());
        update.set("age", users.getAge());
        update.set("gender", users.getGender());
        update.set("country", users.getCountry());

        return mongoTemplate.updateFirst(query, update, Users.class).wasAcknowledged();
    }

    @Override
    public boolean remove(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        return mongoTemplate.remove(query, Users.class).wasAcknowledged();
    }

    @Override
    public List<Users> search() {
        return mongoTemplate.findAll(Users.class);
    }
}

Next step is to create a service interface

package com.java.mongo.service;

import com.java.mongo.model.Users;

import java.util.List;

public interface userService {
    Users save(Users users);
    boolean update(Users users);
    boolean remove(String id);
    List<Users> search();
}

Then implementation of the service interface

package com.java.mongo.service;

import com.java.mongo.dao.userRepository;
import com.java.mongo.model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class userServiceImpl implements userService {

    @Autowired
    private userRepository userRepository;

    @Override
    public Users save(Users users) {
        return userRepository.save(users);
    }

    @Override
    public boolean update(Users users) {
        return userRepository.update(users);
    }

    @Override
    public boolean remove(String id) {
        return userRepository.remove(id);
    }

    @Override
    public List<Users> search() {
        return userRepository.search();
    }
}

After that create a controller class

package com.java.mongo.controller;

import com.java.mongo.model.Users;
import com.java.mongo.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class userController {

    @Autowired
    private userService userService;

    @RequestMapping(value = "/test/mongo/save", method = RequestMethod.POST, consumes = "application/json")
    public String saveData(@RequestBody Users users) {
        Users u = null;

        try {
            userService.save(users);
        } catch (Exception e) {
            return e.getMessage();
        }

        return "Success !";
    }


    @RequestMapping(value = "/test/mongo/search", method = RequestMethod.GET, consumes = "application/json")
    public List<Users> searchData() {
        List<Users> users = null;

        try {
            users = userService.search();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (users.size() != 0) {
            return users;
        } else {
            return null;
        }
    }

    @RequestMapping(value = "/test/mongo/update", method = RequestMethod.PUT, consumes = "application/json")
    public String updateData(@RequestBody Users users) {
        boolean b = false;

        try {
            b = userService.update(users);
        } catch (Exception e) {
            return e.getMessage();
        }

        if (b){
            return "Success !";
        }else {
            return "Error !";
        }
    }

    @RequestMapping(value = "/test/mongo/remove", method = RequestMethod.DELETE, consumes = "application/json")
    public String removeData(@RequestParam String id) {
        boolean b = false;

        try {
            b = userService.remove(id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (b){
            return "Success !";
        }else {
            return "Error !";
        }
    }

}

Finally, you can deploy the application and send the request to the application through Postman. This is the sample JSON payload to testing the application. Once you connect Java to MongoDB perfectly you can test insert, search, update and delete in Mongo DB with the client application. The Mongo Template is an important thing because it provides all inbuilt methods so we don’t have to write more codings.

GIT location – https://github.com/rajithabhanuka/LearnMongoWithJava.git