在本文中,我们将构建一个 Spring Boot REST API,它使用 Spring Data 和 MongoDB 数据库执行创建、读取、更新和删除 (CRUD) 操作。 Spring Data 在包 org.springframework.data.mongodb.repository
中提供了一个 MongoRepository
接口,其中包含 CRUD 操作所需的所有方法。
类似帖子:
我们将创建一个全新的 Spring Boot 应用程序并公开以下使用 MongoDB 数据库执行 CRUD 操作的 API。
HTTP 方法 | 端点 | 行动 |
---|---|---|
POST | api/schools | 将新学校保存到数据库中 |
GET | api/schools | 获取所有学校 |
PUT | api/schools | 更新现有学校 |
DELETE | api/schools/:id | 通过 ID 从数据库中删除现有学校 |
P.S. 每个学校文件都有一个唯一的 ID。
这是 pom.xml 文件,包括此项目中使用的所需依赖项。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.websparrow</groupId>
<artifactId>spring-boot-mongodb-crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-mongodb-crud</name>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
我们在 IntelliJ IDEA 中的应用程序的最终项目结构如下所示:
第一步是在 src/main/resources
文件夹下的 application.properties 文件中配置数据库连接字符串。
application.properties
#Database connection strings
spring.data.mongodb.uri=mongodb://localhost/springboot_mongodb_crud
创建一个具有以下属性的 POJO 类 School
:id、name、establishmentYear、availableCourses 和 strength 并生成它的 Getter 和 Setter……
School.java
package org.websparrow.dto;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class School {
@Id
private String id;
private String name;
private int establishmentYear;
private String[] availableCourses;
private int strength;
// Generates Getters and Setters...
public School() {}
}
@Document
注释标识要持久化到 MongoDB 的域对象。
@Id
注释告诉 MongoDB 为每个文档生成一个唯一的 Id(划定一个标识符)。
创建一个扩展 MongoRepository
的 SchoolRepository
接口。
SchoolRepository.java
package org.websparrow.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import org.websparrow.dto.School;
@Repository
public interface SchoolRepository extends MongoRepository<School, String> {
}
在 SchoolService
接口中声明所有方法来对学校数据执行 CRUD 操作。
SchoolService.java
package org.websparrow.service;
import org.springframework.stereotype.Service;
import org.websparrow.dto.School;
import java.util.List;
import java.util.Map;
@Service
public interface SchoolService {
School create(School school);
List<School> read();
School update(School school);
Map<String, String> delete(String id);
}
SchoolServiceImpl
是 SchoolService
接口的实现类。
SchoolServiceImpl.java
package org.websparrow.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.websparrow.dto.School;
import org.websparrow.repository.SchoolRepository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SchoolServiceImpl implements SchoolService {
@Autowired
private SchoolRepository schoolRepository;
@Override
public School create(School school) {
return schoolRepository.insert(school);
}
@Override
public List<School> read() {
return schoolRepository.findAll();
}
@Override
public School update(School school) {
return schoolRepository.save(school);
}
@Override
public Map<String, String> delete(String id) {
// Total count of data before delete
long beforeDelete = schoolRepository.count();
schoolRepository.deleteById(id);
// Total count of data after delete
long afterDelete = schoolRepository.count();
String messageValue = beforeDelete == afterDelete ? "Something went wrong!" : "Record deleted";
Map<String, String> deleteMap = new HashMap<>();
deleteMap.put("message", messageValue);
return deleteMap;
}
}
Create SchoolController
类处理用户请求以执行相应的创建、读取、更新和删除操作和响应。了解有关 @RestController 和 @Autowired 注释的更多信息。
SchoolController.java
package org.websparrow.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.websparrow.dto.School;
import org.websparrow.service.SchoolService;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("api/schools")
public class SchoolController {
@Autowired
private SchoolService schoolService;
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public School saveSchool(@RequestBody School school) {
return schoolService.create(school);
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<School> getAllSchools() {
return schoolService.read();
}
@PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public School updateSchool(@RequestBody School school) {
return schoolService.update(school);
}
@DeleteMapping("/{id}")
public Map<String, String> deleteSchool(@PathVariable String id) {
return schoolService.delete(id);
}
}
创建一个 SpringBootApp
类并运行它。
SpringBootApp.java
package org.websparrow;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}
现在一切都完成了。让我们测试应用程序。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/spring/spring-boot-mongodb-crud-example
内容来源于网络,如有侵权,请联系作者删除!