Spring Boot + MongoDB CRUD 示例

x33g5p2x  于2021-10-15 转载在 Go  
字(6.1k)|赞(0)|评价(0)|浏览(596)

在本文中,我们将构建一个 Spring Boot REST API,它使用 Spring Data 和 MongoDB 数据库执行创建、读取、更新和删除 (CRUD) 操作。 Spring Data 在包 org.springframework.data.mongodb.repository 中提供了一个 MongoRepository 接口,其中包含 CRUD 操作所需的所有方法。
类似帖子:

  1. Spring Boot 和 MongoDB 入门
  2. 如何连接 Spring Boot 应用程序和 MongoDB
  3. Spring Data MongoRepository 接口方法示例

我们将构建什么

我们将创建一个全新的 Spring Boot 应用程序并公开以下使用 MongoDB 数据库执行 CRUD 操作的 API。

HTTP 方法端点行动
POSTapi/schools将新学校保存到数据库中
GETapi/schools获取所有学校
PUTapi/schools更新现有学校
DELETEapi/schools/:id通过 ID 从数据库中删除现有学校

P.S. 每个学校文件都有一个唯一的 ID。

我们需要什么

  • JDK 1.8 or later
  • Spring Boot 2.3.4.RELEASE
  • Spring Data
  • Gradle 4+ or Maven 3.2+
  • MongoDB 4.4.1 Database
  • Your favorite IDE:
  • Spring Tool Suite (STS)
  • Eclipse
  • IntelliJ IDEA

需要依赖

这是 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 类 SchoolidnameestablishmentYearavailableCourses 和 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(划定一个标识符)。

存储库

创建一个扩展 MongoRepositorySchoolRepository 接口。
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);

}

SchoolServiceImplSchoolService 接口的实现类。

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

测试应用程序

现在一切都完成了。让我们测试应用程序。

相关文章

微信公众号

最新文章

更多