Todo App with Java, Spring Boot and H2 Database

Todo App with Java, Spring Boot and H2 Database

Building a Java Spring Boot Todo Application with H2 Database

Spring Boot is a powerful framework for building web applications in Java. This tutorial will guide you through creating a simple Todo application with an H2 in-memory database.

Prerequisites

  • Java 8 or higher installed

  • Maven or Gradle installed

  • An IDE like IntelliJ IDEA or Eclipse


Step 1: Setting up the Spring Boot Application

Create a Spring Boot Project

  1. Go to Spring Initializr.

  2. Select the following:

    • Project: Maven

    • Language: Java

    • Spring Boot: Latest stable version

    • Dependencies: Spring Web, Spring Data JPA, H2 Database

  3. Click on Generate to download the project.

  4. Unzip the downloaded file and open it in your IDE.

Update application.properties

Configure the H2 database in src/main/resources/application.properties:

spring.datasource.url=jdbc:h2:mem:todoapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

Step 2: Define the Todo Entity

Create an entity class to represent the Todo items.

import jakarta.persistence.*;
import lombok.*;

@Entity
@Data // Lombok annotation for getters, setters, toString, etc.
@NoArgsConstructor
@AllArgsConstructor

public class Todo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    private String description;

    private boolean completed;


    public Long getId() {
        return id;
    }

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

    // Getter and Setter for 'title'
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    // Getter and Setter for 'description'
    public String getDescription() {
        return description;
    }

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

    // Getter and Setter for 'completed'
    public boolean isCompleted() {
        return completed;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }
}

Step 3: Create the Repository

package com.example.todo;

import com.example.todoupdated.todoupdated.model.Todo;
import org.springframework.data.jpa.repository.JpaRepository;

public interface TodoRepository extends JpaRepository<Todo, Long> {
}

Step 4: Build the Service Layer

package com.example.todo;

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

import java.util.List;

@Service
public class TodoService {

    @Autowired
    private TodoRepository todoRepository;

    public List<Todo> getAllTodos() {
        return todoRepository.findAll();
    }
    public Todo getTodoById(Long id) {
        return  todoRepository.findById(id).orElseThrow(() -> new RuntimeException("Todo not found"));
    }

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

    public Todo updateTodo(Long id, Todo todoDetails) {
        System.out.println(todoDetails.getClass().getName());

        Todo todo = getTodoById(id);
        todo.setTitle(todoDetails.getTitle());
        todo.setDescription(todoDetails.getDescription());
        todo.setCompleted(todoDetails.isCompleted());
        return todoRepository.save(todo);
    }

    public void deleteTodoById(Long id) {
        todoRepository.deleteById(id);
    }
}

Step 5: Create the Controller

package com.example.todo;


import com.example.todoupdated.todoupdated.model.Todo;
import com.example.todoupdated.todoupdated.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/todos")

public class TodoController {

    @Autowired
    private TodoService todoService;

    @GetMapping
    public List<Todo> getAllTodos() {
        return todoService.getAllTodos();
    }

    @GetMapping("/{id}")
    public Todo getTodoById(@PathVariable Long id) {
        return todoService.getTodoById(id);
    }

    @PostMapping
    public Todo createTodo(@RequestBody Todo todo) {
        return todoService.createTodo(todo);
    }

    @PutMapping("/{id}")
    public Todo updateTodo(@PathVariable Long id, @RequestBody Todo todoDetails) {
        return todoService.updateTodo(id, todoDetails);
    }

    @DeleteMapping("/{id}")
    public void deleteTodoById(@PathVariable Long id) {
        todoService.deleteTodoById(id);
    }


}

Step 6: Test the Application

Run the Application

  1. Open the terminal in your project directory.

  2. Use the command mvn spring-boot:run to start the application.

Access the H2 Console

  • Open your browser and navigate to http://localhost:8080/h2-console.

  • Use the following credentials:

    • JDBC URL: jdbc:h2:mem:todoapp

    • Username: sa

    • Password: password

Test Endpoints

Use tools like Postman or cURL to test the API endpoints:

  • GET Todos: GET http://localhost:8080/api/todos

  • Create Todo: POST http://localhost:8080/api/todos

      {
        "title": "Learn Spring Boot",
        "completed": false
      }
    
  • Delete Todo: DELETE http://localhost:8080/api/todos/{id}


Conclusion

You’ve built a basic Todo application using Spring Boot and an H2 database. This setup is ideal for rapid prototyping and small projects. From here, you can expand the application by adding user authentication, deploying it to a cloud service, or using a production-grade database like PostgreSQL or MySQL.

GitHub Link: https://github.com/chaitanyamean/java-spring-todo