Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Create Todo List API using Spring Boot and MySQL?
Next article icon

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

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
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.


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

S

shapnesht
Improve
Article Tags :
  • Java
  • Technical Scripter
  • SQL
  • Technical Scripter 2022
  • mysql
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Spring JDBC vs Spring Data JDBC
    Understanding the difference between Spring JDBC and Spring Data JDBC is important for choosing the right approach to interact with relational databases in Spring Boot applications. Both frameworks serve the same purpose but differ significantly in terms of abstraction, ease of use, and developer pr
    5 min read
    Best Practices For Structuring Spring Boot Application
    Spring Boot is built on top of the conventional spring framework. So, it provides all the features of spring and is yet easier to use than spring. In this article, we are going to see how one should start and structure his Spring Boot application. Prerequisites: Good knowledge of Java.Basic knowledg
    3 min read
    Spring Boot - Start/Stop a Kafka Listener Dynamically
    In a Spring Boot application, Kafka Listeners start automatically once the application launches and they listen for messages from Kafka topics. But there are many scenarios where we might need to dynamically start or stop a Kafka listener based on certain conditions. This can be achieved using Kafka
    6 min read
    How To Dockerize A Spring Boot Application With Maven ?
    Docker is an open-source containerization tool that is used for building, running, and managing applications in an isolated environment. It facilitates the developers to bundles its software, libraries, and configuration files. The Docker facilitates with isolating the one container from another. In
    12 min read
    Dynamic Dropdown From Database using Spring Boot
    The concept of dynamic dropdown (or dependent dropdown) is exciting and challenging to code. Dynamic dropdown means that the values in one dropdown list are dependent on the value selected in the previous dropdown list. A simple example would be three dropdown boxes displaying names of the district,
    11 min read
    Spring - RestTemplate
    Due to high traffic and quick access to services, REST APIs are getting more popular and have become the backbone of modern web development. It provides quick access to services and also provides fast data exchange between applications. REST is not a protocol or a standard, rather, it is a set of ar
    7 min read
    Spring Boot - Scheduling
    Spring Boot provides the ability to schedule tasks for execution at a given time period with the help of @Scheduled annotation. This article provides a step by step guideline on how we can schedule tasks to run in a spring boot application Implementation:It is depicted below stepwise as follows:  St
    4 min read
    Spring Boot - Sending Email via SMTP
    Spring Boot provides the ability to send emails via SMTP using the JavaMail Library. Here we will be illustrating step-by-step guidelines to develop Restful web services that can be used to send emails with or without attachments. In order to begin with the steps, let us first create a Spring Boot p
    5 min read
    Different Ways to Establish Communication Between Spring Microservices
    If you are working with a Spring Boot project which involves multiple microservices, You might have felt the need to communicate from microservice m1 to microservice m2. Depending upon business use-cases, this communication can be of synchronous or asynchronous type. Before digging dip further. Let'
    3 min read
    JSON using Jackson in REST API Implementation with Spring Boot
    When we build REST APIs with Spring Boot, we need to exclude NULL values from the JSON responses. This is useful when we want to optimize the data being transferred, making the response more compact and easier to process for the client.In this article, we are going to learn the approach that is used
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences