Log in
Sign up
Documentation
  • - Quick start guides
  • - How Jumpydoll works
  • - Tutorials
  • - Java/Spring Boot tutorial
  • - Step 1: Introduction
  • - Step 2: Setting up the project
  • - Step 3: Building the first API endpoint
  • - Step 4: Storing data in MongoDB Atlas
  • - Step 5: Adding more API endpoints
  • - Step 6: Creating a user interface
  • - Step 7: Conclusion

Step 4: Storing data in MongoDB Atlas - Java/Spring Boot tutorial

In this step, you will update your Task class to store data in MongoDB using MongoDB Atlas.

Introduction to MongoDB

Right now, your to-do list API can only return a result that you add to the code. You’ll want to be able to dynamically add and retrieve tasks into the list. To store the list of tasks, you’ll need to connect to a database. This tutorial will walk you through using MongoDB with MongoDB Atlas.

MongoDB is a document-based, NoSQL database. Data is stored as a collection of JSON documents, which can be queried by the different fields of the document. A document-based database is a much simpler way of storing simple collections, compared to a relational database.

In order to host and manage a MongoDB database, we will be using MongoDB Atlas. MongoDB Atlas is a service created by the MongoDB team that provides a completely managed version of MongoDB. What this means is that you can simply connect to your database without having to worry about managing a server to run the database. MongoDB Atlas has a free shared tier to help you learn how to use the database. This free tier has plenty of resources for this tutorial project, as well as many future side-projects you may develop.

Setting up your database in MongoDB Atlas

To set up your database in MongoDB Atlas follow these steps:

  • Go to MongoDB Atlas (https://www.mongodb.com/atlas/database) and sign up for an account.

  • Create a new project, and call it jumpydoll-todo-list.

  • Click “Build a database”

  • Select the “Shared tier”

  • Choose a provider and region (we recommend Google Cloud in the Iowa us-central1 region)

  • Click the “Create cluster” button

  • To authenticate with the database, create a user with a username and password. Make sure you remember the password since you’ll need it to connect with the database.

  • For the allowed IP addresses, add 0.0.0.0/0 to the list (this allows connections from any IP address)

  • Click on “Finish and Close”

  • On the “Database” page, click the “Connect button”

  • Select “Connect your application” and choose Java with version 4.3 or later. Copy the connection string, replacing <password> with the password from earlier. Save this connection string as you’ll need it later.

Connect to the database

Now that your database has been created, you’ll need to connect your Spring service to the database. To do this, we will be using a new dependency that allows us to interact with MongoDB directly with Spring. We will be using Maven to import the new dependency. To add the Spring Boot MongoDB dependency, open the pom.xml file in your project. In the <dependencies> section, add the following dependency:

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

After adding the dependency, load the Maven changes in with your IDE so you can start using the new dependency.

To provide credentials for your app to authenticate, open the src/main/resources/application.properties file and add the following two lines

spring.data.mongodb.uri=${MONGODB_CONNECTION_URI}
spring.data.mongodb.database=todo-list

This will use a database called todo-list in the cluster you created on MongoDB Atlas. The connection string will be pulled from the MONGODB_CONNECTION_URI environment variable. To set the environment variable follow these steps:

  • Click Run > Edit Configurations

  • Click on “Modify” next to Java Options and select “Environment Variables”

  • In the “Environment Variables” box, put MONGODB_CONNECTION_URI=<your_connection_string>, replacing <your_connection_string> with the connection string you saved earlier.

  • Click OK to save the configuration

Now, Spring will read the credentials from the MONGODB_CONNECTION_URI environment variable and connect to MongoDB.

Updating the Task model

Now that you have the required dependencies to use MongoDB with Spring Boot, it’s time to integrate our application to read and save data to your MongoDB database. Spring boot uses a component called a repository to handle connections to various data sources. The repository allows you to connect to a variety of databases using a consistent interface. We will create a repository that connects to MongoDB.

Create a package called repository in the com.jumpydoll.app.[user].jumpydolltodolist package.

Create a new interface called TaskRepository in the package. Make your interface extend MongoRepository<Task, String>. Your interface should look like the following:

src/main/java/com/jumpydoll/app/[user]/jumpydolltodolist/repository/TaskRepository.java

package com.jumpydoll.app.[user].jumpydolltodolist.repository;

import com.jumpydoll.app.[user].jumpydolltodolist.model.Task;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface TaskRepository extends MongoRepository<Task, String> {
}

This creates a new repository that knows how to access the MongoDB database and return data in the form of a Task object that your application uses. This is all you need to get started since the MongoRepository already contains basic methods for interacting with MongoDB. If you want to perform more complex data queries in the future, you can add your own methods to this repository. If you want to learn more, check out https://spring.io/guides/gs/accessing-data-mongodb.

To make sure the repository knows how to work with your Task class, you will need to add the proper annotations to the Task class. Add the @Document(“tasks”) annotation to the class to store Tasks in a collection called “tasks”. Then add the @Id annotation to the id field of the Task. Your Task class should look like this:

/src/main/java/com/jumpydoll/app/[user]/jumpydolltodolist/model/Task.java

package com.jumpydoll.app.[user].jumpydolltodolist.model;

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

@Document("task")
public class Task {
    @Id
    String id;
    String description;
    long createTime;
    boolean finished;

    // Constructor, getters, and setters...

}
Retrieving data from MongoDB

Before you add your first API to save data, you’ll need to add the TaskRepository to your TodoController so your API code can interact with the database. To do this, add a TaskRepository field with the @Autowired annotation. The @Autowired annotation tells Spring to automatically create an instance of a TaskRepository and set it in the Controller object when you start the application.

@Autowired
TaskRepository taskRepository;

Now that your controller can access the database, update the getTasks method to read from the taskRepository using the findAll() method. Your TodoController should look like this:

src/main/java/com/jumpydoll/app/[user]/jumpydolltodolist/controller/TodoController.java

package com.jumpydoll.app.[user].jumpydolltodolist.controller;

import com.jumpydoll.app.[user].jumpydolltodolist.model.Task;
import com.jumpydoll.app.[user].jumpydolltodolist.repository.TaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class TodoController {
    @Autowired
    TaskRepository taskRepository;

    @GetMapping(value = "/api/tasks")
    public ResponseEntity<?> getTasks() {
        List<Task> todoList = taskRepository.findAll();
        return new ResponseEntity<>(todoList, HttpStatus.OK);
    }
}

If you visit http://localhost:8080/jumpydoll-todo-list/api/tasks, you will now get an empty array []. This is because nothing has been added to the database yet.

Now that your API can now read from the database, you will want to add APIs that allow you to save data.

Creating a POST API to save data

The getTasks method is mapped to an HTTP GET endpoint. The HTTP GET method is used primarily for reading data. For creating data, developers use the HTTP POST method.

Create a new method called createTask. This method should accept a task that we need to create and return a ResponseEntity<Task>. Since this is a create method, we’ll want to use the POST method. Add the following annotation to the method

@PostMapping(value = "/api/tasks", consumes = MediaType.APPLICATION_JSON_VALUE) 

PostMapping tells Spring that this method should be called when it receives an HTTP POST request to the URL. The consumes argument tells Spring that it should accept JSON input.

Annotate the task parameter with @RequestBody. This tells Spring to automatically convert the JSON in the HTTP body into the Task object.

From there, set the create time to the current system time and the finished value to false, since we want tasks to start off as incomplete. Set the id to null, since we want MongoDB to automatically generate the ID. Then call taskRepository.insert(task) to save the Item to MongoDB. The returned value will contain the item that was saved, including the generated ID. You can then return the saved object, with the HttpStatus of CREATED. Your method should like the following:

@PostMapping(value = "/api/tasks", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Task> createTask(@RequestBody Task task) {
    task.setCreateTime(System.currentTimeMillis());
    task.setFinished(false);
    task.setId(null);
    Task savedItem = taskRepository.insert(task);
    return new ResponseEntity<>(savedItem, HttpStatus.CREATED);
}
Testing the new methods

When you visit a URL in your browser, your browser makes an HTTP GET request to the URL. However, to make a POST request in a browser, the web page must have Javascript code to make the POST request. In the last step of this tutorial, you'll learn how to make a POST request in Javascript, but for now, you can use a REST client to test your API. Some popular REST clients include:

To test your API with curl, open Command Prompt on Windows or Terminal on macOS/Linux. Paste the following command and press enter.

curl -X GET http://localhost:8080/jumpydoll-todo-list/api/tasks

This calls the getTasks method and returns an empty list, as data hasn't been added yet.

To add data, run:

curl -X POST http://localhost:8080/jumpydoll-todo-list/api/tasks -H 'Content-Type:application/json' -d '{"description": "Add and UPDATE and DELETE method"}'

You should see a response containing the created item, like

{"id":"62ba10eb81664f0d0ab25eea","description":"Add and UPDATE and DELETE method","createTime":1656361195961,"finished":false}

Run the GET curl command again and you should now see your created task. Now that you can add data to your to-do list, the next step is to handle update and delete operations.

Step 3: Building the first API endpointStep 5: Adding more API endpoints
Try Jumpydoll and host your own project

• Sign up with a GitHub account
• No setup required - start right in your browser
• Start your first project in 5 minutes
Get started for free

Jumpydoll

About

Project Gallery

Sign up

Contact

Email: brian@jumpydoll.com

© 2022