Open In App

How to Create Todo List API using Spring Boot and MySQL?

Improve
Improve
Like Article
Like
Save
Share
Report

Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. In this article, we are going to create a simple To-Do List application using Spring Boot and MySQL.

Prerequisites:

  • Good knowledge of Java.
  • Basic knowledge about  Spring Boot.
  • Basic knowledge about Creating REST API with SpringBoot.

To create an application in spring boot make sure you have cleared all the previously listed concepts.

Step By Step Procedure

Step 1: First go to spring initializer and create a new project using the following data given below:

Project: Maven
Language: Java
Spring Boot: 3.0.0
Packaging: JAR
Java: 8 
Dependencies: Spring Web, Spring Data JPA, MySQL Driver
Spring Initializr

Spring Initializr

Now Click on Generate and a .zip file will be downloaded which will be our starter project.

Step 2: Now extract the given folder and then open this project in your preferred IDE, Here I will use IntelliJ Idea Community edition for that, To open this starter project just click on open and then select the extracted folder from your files.

Opening Project in IntelliJ Idea Community edition

Opening Project in IntelliJ Idea Community edition

After clicking on OK you’ll see a screen that is like the below one.

IntelliJ Idea

IntelliJ Idea

Note: If something went wrong then you can Right Click on pom.xml > maven > Reload project and after this, some processing will take place and you’ll be ready to go.

Step 3: Now create 4 packages in the following folder -> src > main > java > com.example.demo Now right-click on this folder > new > package > give name > press enter

Creating package

Creating package

The packages will be the following:

  1. controllers
  2. services
  3. repositories
  4. models

The file tree will look like the one below after you create the above-listed packages.

File tree after creating the packages

File tree after creating the packages

Step 4: Create a new database named todolist to open MySQL Command Line Client and then execute the command 

create database todolist;
MySQL Command Line Client

MySQL Command Line Client

After creating this database we will use it in the future.

Step 5: Now we’ll configure the application.properties file and add the following information so as to establish the connection with the database which will be MySQL in our case, replace the username with the username of your MySQL(default: root) and your account’s password should be written in the spring.datasource.password field

application.properties file

application.properties file

Here are the properties if you want to copy the given properties:

# This is the property to specify the database and the driver here todolist is database name and mysql is driver
spring.datasource.url=jdbc:mysql://localhost:3306/todolist

# These properties specify the data used for authentication and authorization for the database
spring.datasource.username= {use Your username here}
spring.datasource.password= {use Your password here}

# This property is used to specify how we'll handle data ex:- update -> update the remaining data,
# ex: create-drop -> everytime create new tables and delete on termination of the program
spring.jpa.hibernate.ddl-auto=update

# Driver Class for MySQL
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# This is used to show sql whenever any query is executed by hibernate
spring.jpa.show-sql: true

Step 6: Now that we have set up everything we are going to create a model which will help us to create a table in the database. We’ll create a class in the models package and we’ll name the class Task.java which will contain the following data

Java




package com.example.demo.models;
  
import jakarta.persistence.*;
  
@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    // this is the primary key which will be auto generated
    private Long id;
    private String task;
    private boolean completed;
  
    public Task(String task, boolean completed) {
        this.task = task;
        this.completed = completed;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getTask() {
        return task;
    }
    public void setTask(String task) {
        this.task = task;
    }
    public boolean isCompleted() {
        return completed;
    }
    public void setCompleted(boolean completed) {
        this.completed = completed;
    }
}


Step 7: Now we’ll create an interface named TaskRepository inside the package repositories and It will extend the interface JPARepository<Task, Long>, and here Task is our model and Long is the primary id’s datatype that we declared in the Task.java file

Java




package com.example.demo.repositories;
  
import com.example.demo.models.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
  
import java.util.List;
  
@Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
    public Task findByTask(String task);
    public List<Task> findByCompletedTrue();
    public List<Task> findByCompletedFalse();
    public List<Task> findAll();
    public Task getById(Long id);
}


Step 8: Now that we have created our Repositories and models we’ll create our service class and we’ll implement all the business logic in this class so create a new class TaskService in the services package.

Java




package com.example.demo.services;
  
import com.example.demo.models.Task;
import com.example.demo.repositories.TaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
  
import java.util.List;
  
@Service
public class TaskService {
    @Autowired
    private TaskRepository taskRepository;
      
    public Task createNewTask(Task task) {
        return taskRepository.save(task);
    }
      
    public List<Task> getAllTask() {
        return taskRepository.findAll();
    }
      
    public Task findTaskById(Long id) {
        return taskRepository.getById(id);
    }
      
    public List<Task> findAllCompletedTask() {
        return taskRepository.findByCompletedTrue();
    }
      
    public List<Task> findAllInCompleteTask() {
        return taskRepository.findByCompletedFalse();
    }
      
    public void deleteTask(Task task) {
        taskRepository.delete(task);
    }
      
    public Task updateTask(Task task) {
        return taskRepository.save(task);
    }
}


Step 9: Now at the last step we will create the controllers to specify the endpoints and then perform the tasks, Here we have performed all the CRUD applications and now we’ll test that.

Java




package com.example.demo.controllers;
  
import com.example.demo.models.Task;
import com.example.demo.services.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
  
import java.util.List;
  
@Controller
@RequestMapping("/api/v1/tasks")
public class TaskController {
  
    @Autowired
    private TaskService taskService;
    @GetMapping("/")
    public ResponseEntity<List<Task>> getAllTasks() {
        return ResponseEntity.ok(taskService.getAllTask());
    }
    @GetMapping("/completed")
    public ResponseEntity<List<Task>> getAllCompletedTasks() {
        return ResponseEntity.ok(taskService.findAllCompletedTask());
    }
    @GetMapping("/incomplete")
    public ResponseEntity<List<Task>> getAllIncompleteTasks() {
        return ResponseEntity.ok(taskService.findAllInCompleteTask());
    }
    @PostMapping("/")
    public ResponseEntity<Task> createTask(@RequestBody Task task) {
        return ResponseEntity.ok(taskService.createNewTask(task));
    }
    @PutMapping("/{id}")
    public ResponseEntity<Task> updateTask(@PathVariable Long id, @RequestBody Task task) {
        task.setId(id);
        return ResponseEntity.ok(taskService.updateTask(task));
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<Boolean> getAllTasks(@PathVariable Long id) {
        taskService.deleteTask(id);
        return ResponseEntity.ok(true);
    }
}


Step 10: Now Start the given program by opening the ToDoListApplication.java and clicking on the run button, Here We have the following endpoints to perform the following tasks also we are going to use Postman to make the requests to our server :

GET /api/v1/tasks -> returns all the tasks

Get Request

POST /api/v1/tasks -> saves new Task to the database

Post request

GET /api/v1/tasks/completed -> returns list of all the completed task

Completed tasks

GET /api/v1/tasks/incomplete -> returns list of all the incomplete task

Incomplete tasks

PUT /api/v1/tasks/id -> updates the task with given id and details

Update task with the PUT request

DELETE /api/v1/tasks/id -> deletes the task with given id from the database

Delete task using the task id

So finally we have created our To Do List application.



Last Updated : 01 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads