第一步:创建项目
第二步:给mongodb插入数据
第三步:创建实体类
package org.cyl.test02.entity;// Task.java
import lombok.Data;@Data
public class Task {private String id;private String description;
}
第四步:创建Repository
引入依赖
<!-- Spring Data MongoDB --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb-reactive</artifactId></dependency>
创建TaskRepository接口
package org.cyl.test02.repository;// TaskRepository.java
import org.cyl.test02.entity.Task;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;public interface TaskRepository extends ReactiveCrudRepository<Task, String> {}
第五步:创建Controller
package org.cyl.test02.controller;// TaskController.java
import org.cyl.test02.entity.Task;
import org.cyl.test02.repository.TaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;@RestController
@RequestMapping("/tasks")
public class TaskController {@Autowiredprivate TaskRepository taskRepository;@GetMappingpublic Flux<Task> getAllTasks() {return taskRepository.findAll();}@GetMapping("/{id}")public Mono<Task> getTaskById(@PathVariable String id) {return taskRepository.findById(id);}@PostMappingpublic Mono<Task> createTask(@RequestBody Task task) {return taskRepository.save(task);}@PutMapping("/{id}")public Mono<Task> updateTask(@PathVariable String id, @RequestBody Task task) {task.setId(id);return taskRepository.save(task);}@DeleteMapping("/{id}")public Mono<Void> deleteTask(@PathVariable String id) {return taskRepository.deleteById(id);}
}
第六步:配置yml文件
spring:data:mongodb:uri: mongodb://localhost:27017/student