Spring Data MongoDB 操作 document DB 的详细示例

news/2024/10/6 21:53:31/文章来源:https://www.cnblogs.com/gongchengship/p/18290961

使用 Spring Data MongoDB 操作 AWS DocumentDB 是一种高效且常见的做法。以下是详细的示例,展示如何配置和使用 Spring Data MongoDB 连接和操作 AWS DocumentDB。

步骤 1:添加 Maven 依赖

pom.xml 文件中添加 Spring Data MongoDB 和 Spring Boot Starter Web 的依赖:

<dependencies><!-- Spring Boot Starter Data MongoDB --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency><!-- Spring Boot Starter Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Boot Starter Test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>

步骤 2:配置 Spring Boot 应用

application.propertiesapplication.yml 文件中添加 MongoDB 连接配置:

# application.yml
spring:data:mongodb:uri: mongodb://<username>:<password>@<documentdb-endpoint>:<port>/<database>?ssl=true&retryWrites=falsedatabase: <database>

步骤 3:创建实体类和仓库接口

创建一个简单的用户实体类:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;@Document(collection = "users")
public class User {@Idprivate String id;private String name;private String email;// Getters and setterspublic String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}
}

创建一个用户仓库接口:

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;@Repository
public interface UserRepository extends MongoRepository<User, String> {
}

步骤 4:使用仓库进行数据操作

在服务类中使用 UserRepository 进行数据操作:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserService {@Autowiredprivate UserRepository userRepository;public User saveUser(User user) {return userRepository.save(user);}public User findUserById(String id) {return userRepository.findById(id).orElse(null);}public List<User> findAllUsers() {return userRepository.findAll();}public void deleteUserById(String id) {userRepository.deleteById(id);}
}

步骤 5:创建控制器

创建一个控制器来处理用户的 HTTP 请求:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/users")
public class UserController {@Autowiredprivate UserService userService;@PostMappingpublic User createUser(@RequestBody User user) {return userService.saveUser(user);}@GetMapping("/{id}")public User getUserById(@PathVariable String id) {return userService.findUserById(id);}@GetMappingpublic List<User> getAllUsers() {return userService.findAllUsers();}@DeleteMapping("/{id}")public void deleteUserById(@PathVariable String id) {userService.deleteUserById(id);}
}

步骤 6:启动类

确保你的 Spring Boot 应用启动类位于正确的包下,并启用了 Spring Data MongoDB:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DocumentDbApplication {public static void main(String[] args) {SpringApplication.run(DocumentDbApplication.class, args);}
}

总结

通过上述步骤,你可以使用 Spring Data MongoDB 连接和操作 AWS DocumentDB。这种方法充分利用了 Spring Data MongoDB 的特性,使得操作文档数据库更加高效和简便。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/740880.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

全网最适合入门的面向对象编程教程:11 类和对象的Python实现-子类调用父类方法-模拟串口传感器和主机

本节课,我们主要讲解了在Python类的继承中子类如何进行初始化、调用父类的属性和方法,同时讲解了模拟串口传感器和主机类的具体实现,并使用xcom串口助手与两个类进行串口通信使用。全网最适合入门的面向对象编程教程:11 类和对象的 Python 实现-子类调用父类方法-模拟串口传…

Vite5+Electron聊天室|electron31跨平台仿微信EXE客户端|vue3聊天程序

基于electron31+vite5+pinia2跨端仿微信Exe聊天应用ViteElectronChat。 electron31-vite5-chat原创研发vite5+electron31+pinia2+element-plus跨平台实战仿微信客户端聊天应用。实现了聊天、联系人、收藏、朋友圈/短视频等模块。支持electron多开窗口管理、壁纸皮肤、自定义最大…

隐私计算核心技术

非对称加密算法 RSA RSA 算法基础欧拉函数:任意给定正整数 n,在小于等于 n 的正整数中,有多少个数与 n 构成互质关系?计算这些值的方法叫做欧拉函数,以 \(\varphi(n)\) 表示。 欧拉定理:如果两个正整数 a 和 n 互质,则 n 的欧拉函数可以让下面的等式成立:\[\begin{equa…

[Code Composer Studio] Memory Browser保存数据

造冰箱的大熊猫,适用于Code Composer Studio v5.5@cnblogs 2024/7/91、使用CCS>>View>>Memory Browser,可对目标板上的存储空间进行读写操作 2、要保存数据,在Memory Browser内,点击鼠标右键,在弹出的菜单中选择Save Memory 3、在Save Memory对话框中,在Fi…

[LeetCode] 135. Candy

和 238. Product of Array Except Self 计算除自己之外的乘积很像,先左侧遍历,再右侧遍历。 Hard不过如此。 class Solution:def candy(self, ratings: List[int]) -> int:# 1n = len(ratings)if n == 1:return 1# min element is not existif all(x == ratings[0] for x …

常用类

常用类 内部类 分类成员内部类 静态内部类 static 局部内部类 匿名内部类概念:在一个类的内部再定义一个完整的类 class Outer{class Inner{} }特点:编译之后可生成独立的字节码文件 (.class) 内部类可直接访问外部类的私有成员,而不破坏封装 可为外部类提供必要的内部…

一台 3000 元战未来主机装配方案

为了更好的阅读体验,请点击这里 下面是一个备选方案: CPU:酷睿I3 12100 四核八线程649 主板:微星H610M 爆破弹 金牌 569 内存:金百达16G 8GX2 3200 银爵 229 散热:赛普雷 涂城 双铜管散热器 49 固态:西数SN570 500G M2新蓝盘 249 显卡:UHD 730 电源:航嘉 GS400 好运来…

算法金 | 时间序列预测真的需要深度学习模型吗?是的,我需要。不,你不需要?

大侠幸会,在下全网同名「算法金」 0 基础转 AI 上岸,多个算法赛 Top 「日更万日,让更多人享受智能乐趣」参考 论文:https://arxiv.org/abs/2101.02118 更多内容,见微*公号往期文章: 审稿人:拜托,请把模型时间序列去趋势!! 使用 Python 快速上手 LSTM 模型预测时间序列…

Pandas我这个填充nan值为什么填充不上呢?

大家好,我是Python进阶者。 一、前言 前几天在Python钻石交流群【逆光】问了一个Python数据处理的问题,问题如下:请问一下,我这个填充nan值为什么填充不上呢二、实现过程 这里【瑜亮老师】给了个思路如下:试试看这样,代码如下: sf_mergetotal.loc[sf_mergetotal[寄件人]…

python matplot绘图工具练习

matplot 数据可视化 seaborn# pyplot import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pdx_point = np.array([0,6]) y_point = np.array([0,100]) plt.plot(x_point,y_point,b-.v) # 格式处理 plt.show()x = np.arange(0,4…

R语言用逻辑回归、决策树和随机森林对信贷数据集进行分类预测|附代码数据

原文链接:http://tecdat.cn/?p=17950 最近我们被客户要求撰写关于的研究报告,包括一些图形和统计输出。在本文中,我们使用了逻辑回归、决策树和随机森林模型来对信用数据集进行分类预测并比较了它们的性能数据集是 credit=read.csv("gecredit.csv", header = T…

代码随想录算法训练营第27天 | 122.买卖股票的最佳时机 II 55. 跳跃游戏 1005.K次取反后最大化的数组和

122.买卖股票的最佳时机 II 给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。 在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。 返回 你能获得的 最大 利润 。 解题: 思路:最…