spring boot spring data mongo crud example

 


Spring boot spring data MongoDB crud example tutorial that explains how to create a REST api using Spring boot 2, Spring data jpa and mongoDB database.

This tutorial is a modification of the tutorial Spring Boot Spring Data H2 database tutorial.

Adding Spring data Mongo maven dependency

MongoDB is a very famous noSql database that supports reactive programming.

You should install MongoDB community using this link in order to follow this tutorial.

The dependency to be added to the maven POM file is the following :

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

Setting up MongoDB database using the application.properties file

In the application.properties files, we provide the connection url, the jdbc driver, the username, the password and all the database settings.

The database settings are the followings :

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydb

Updating the REST API to use MongoDB database

In order to update the Spring Boot Spring Data JPA H2 database CRUD example, we will :

  • Update the model to add MongoDB annotations
  • Update the repository that makes the CRUD operations
  • Update the service that uses this repository
  • Update the controller that uses this service

Rest API Model

We will add the Mongo annotations to the Todo entity in order to make it managed by Spring Data Mongo.

The required annotations are :

·        @Document : to make the class a MongoDB document

·        @Id : to make a field a primary key

In this class, we can get rid of Getters, Setters and constructors by using lombok. But, i don’t do it for the sake of simplicity and to make the beginners understand the code.

The code of the class is the following :

package com.javasneo.todolist.model;

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

@Document(collection = "todo")
public class Todo {

  @Id
  private String id;
  private String name;
  private String description;

  public Todo() {
  }

  public Todo(String id, String name, String description) {
    this.id = id;
    this.name = name;
    this.description = description;
  }

  public String getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

  public String getDescription() {
    return description;
  }

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

  public void setDescription(String description) {
    this.description = description;
  }
}

Rest API Repository

The repository is a java interface with no java class implementing it. This is a spring Data MongoDB feature that auto-generates the CRUD code for us based on an interface that we specify.

The code of the repository is the following :

package com.javasneo.todolist.repository;

import com.javasneo.todolist.model.Todo;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface TodoRepository extends MongoRepository<Todo, String> {
}

The TodoRepository interface should extend the Spring Data MongoDB interface MongoRepository and give two parameters to that interface :

  • The first one is the Type of the Entity that we will generate the CRUD code for.
  • The second one is the type of the primary key of the entity (the id attribute in the Todo class is of type String)

Rest API Service

The service layer of the application is composed by the interface of the service and its implementation.

The source code of the interface is the following :

package com.javasneo.todolist.service;

import com.javasneo.todolist.model.Todo;

import java.util.List;

public interface TodoService {
  List<Todo> getAll();
  Todo saveOrUpdate(Todo todo);
  void delete(String id);
}

The source code of the implementation is the following :

package com.javasneo.todolist.service;

import com.javasneo.todolist.model.Todo;

import java.util.List;

public interface TodoService {
  List<todo> getAll();
  Todo saveOrUpdate(Todo todo);
  void delete(String id);
}
The source code of the implementation is the following :
package com.javasneo.todolist.service;

import com.javasneo.todolist.model.Todo;
import com.javasneo.todolist.repository.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TodoServiceImpl implements TodoService{
  @Autowired
  TodoRepository todoRepository;

  public List<Todo> getAll(){
    List<Todo> todoList = new ArrayList<Todo>();
    todoRepository.findAll().forEach(todo -> todoList.add(todo));
    return todoList;
  }

  public Todo saveOrUpdate(Todo todo)
  {
    return todoRepository.save(todo);
  }

  public void delete(String id)
  {
    todoRepository.deleteById(id);
  }

}

Rest API controller

The controller uses the service layer to provide the CRUD endpoints.

The source code of the controller is the following :


package com.javasneo.todolist.controller;

import com.javasneo.todolist.model.Todo;
import com.javasneo.todolist.model.TodoListResponse;
import com.javasneo.todolist.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Abderrahmen on 31/01/2018.
 */
@RestController
@RequestMapping("/todos")
@CrossOrigin()
public class TodoController {

  @Autowired
  TodoService todoService;

  @RequestMapping(method = RequestMethod.GET)
  public TodoListResponse todos (){
    List<Todo> todoList = todoService.getAll();
    TodoListResponse todoListResponse = new TodoListResponse();
    todoListResponse.setTodos(todoList);
    return todoListResponse;
  }

  @RequestMapping(method = RequestMethod.POST)
  public Todo addtodo (@RequestBody Todo todo){
    return todoService.saveOrUpdate(todo);
  }


  @RequestMapping(method = RequestMethod.PUT)
  public Todo updateTodo (@RequestBody Todo todo){
    return todoService.saveOrUpdate(todo);
  }

  @RequestMapping(value="/{id}", method = RequestMethod.DELETE)
  public void deleteTodo (@PathVariable("id") String id){
    todoService.delete(id);
  }

}
 

Spring Boot REST API Testing

If you want to know how to test the endpoints using Postman, please check the part 1 of these series of tutorials that deal with Spring Boot 2 REST API.

In order to check the data in MongoDB, we use MongoDB compass integrated by default in MongoDB community edition.

This is the UI of the connection to the database : mongodb://localhost:27017

Here, we haven’t specified a login and a password for mongoDB in the application.properties.

We can do it using these lines of code :

spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=abderrahmen
spring.data.mongodb.password=password

mongoDB compass connect ui

When clicking on connect, we can see our database mydb and our collection todo.

conclusion

this spring boot spring data Mongo crud example tutorial arrives at its end.

You may check also our core java tutorial to learn core java from scratch. Please keep tuned because we will release more tutorials about Spring Boot, unit testing, integration testing and other important subjects.

In order to get our latest updates, please feel free to like our how to program facebook page.

The source code of this tutorial is present in the github of the author Abderrahmen Ben Mariem.



Post a Comment

Previous Post Next Post