Spring Boot教程之四十二:实例-使用 Spring Boot 和 MySQL 创建待办事项列表 API

如何使用 Spring Boot 和 MySQL 创建待办事项列表 API?

Spring Boot 建立在 Spring 之上,包含 Spring 的所有功能。由于其快速的生产就绪环境,使开发人员能够直接专注于逻辑,而不必费力配置和设置,因此如今它正成为开发人员的最爱。Spring Boot 是一个基于微服务的框架,在其中创建生产就绪的应用程序只需很少的时间。在本文中,我们将使用 Spring Boot 和 MySQL创建一个简单的待办事项列表应用程序。

先决条件:

  • 熟悉 Java。
  • 关于 Spring Boot 的基本知识。
  • 有关使用 SpringBoot 创建 REST API 的基本知识。

要在 Spring Boot 中创建应用程序,请确保您已清除所有前面列出的概念。

逐步程序

步骤 1:首先转到spring 初始化程序并使用下面给出的数据创建一个新项目:

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

Spring 初始化

现在单击“生成” ,将下载一个.zip文件,这将是我们的启动项目。

第 2 步:现在提取给定的文件夹,然后在您喜欢的 IDE 中打开此项目,在这里我将使用 IntelliJ Idea 社区版,要打开这个启动项目,只需单击打开,然后从您的文件中选择提取的文件夹。

在 IntelliJ Idea 社区版中打开项目

单击“确定”后,您将看到如下所示的屏幕。

IntelliJ Idea

注意:如果出现问题,您可以右键单击 pom.xml > maven > Reload project,然后进行一些处理,然后您就可以开始了。

步骤 3:现在在以下文件夹中创建 4 个包 -> src > main > java > com.example.demo现在右键单击此 > new > package > give name > 按 Enter

创建包

这些程序包如下:

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

创建上面列出的包后,文件树将如下所示。

创建包后的文件树

步骤4:创建一个名为todolist的新数据库,打开MySQL Command Line Client,然后执行命令 

create database todolist;

MySQL 命令行客户端

创建这个数据库后我们将在将来使用它。

步骤 5:现在我们将配置application.properties文件并添加以下信息,以便与数据库建立连接,在我们的例子中是MySQL,将用户名替换为您的 MySQL 用户名(默认值:root),并且您的帐户密码应写入spring.datasource.password字段

application.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

步骤 6:现在我们已经设置好了一切,我们将创建一个模型,它将帮助我们在数据库中创建一个表。我们将在models包中创建一个类,并将该类命名为Task.java,它将包含以下数据

  • 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;

    }

}

步骤 7:现在我们将在包存储库中创建一个名为TaskRepository 的接口,它将扩展接口 JPARepository<Task, Long>,这里 Task 是我们的模型,Long 是我们在 Task.java 文件中声明的主要 id 数据类型

  • 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);

}

步骤 8:现在我们已经创建了存储库和模型,我们将创建服务类,并在此类中实现所有业务逻辑,因此在服务包中创建一个新类TaskService

  • 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);

    }

}

步骤 9:现在在最后一步,我们将创建控制器来指定端点,然后执行任务,在这里我们已经执行了所有的 CRUD 应用程序,现在我们将对其进行测试。

  • 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);

    }

}

步骤 10:现在通过打开ToDoListApplication.java并单击运行按钮来启动给定的程序,这里我们有以下端点来执行以下任务,我们还将使用Postman向我们的服务器发出请求:

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

获取请求

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

发布请求

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

已完成的任务

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

未完成的任务

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

使用 PUT 请求更新任务

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

使用任务 ID 删除任务

最后我们创建了我们的待办事项列表应用程序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潜洋

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值