Spring Boot中怎么操作MongoDB
发表于:2025-11-08 作者:千家信息网编辑
千家信息网最后更新 2025年11月08日,这期内容当中小编将会给大家带来有关Spring Boot中怎么操作MongoDB,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。新建一个Java项目,pom.xml的
千家信息网最后更新 2025年11月08日Spring Boot中怎么操作MongoDB
这期内容当中小编将会给大家带来有关Spring Boot中怎么操作MongoDB,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
新建一个Java项目,pom.xml的内容如下:
4.0.0 org.springframework gs-rest-service 0.1.0 org.springframework.boot spring-boot-starter-parent 2.0.3.RELEASE org.springframework.boot spring-boot-starter-web org.mongodb mongodb-driver 3.6.4 org.springframework.boot spring-boot-starter-test test com.jayway.jsonpath json-path test org.springframework.boot spring-boot-starter-data-mongodb 1.8 org.springframework.boot spring-boot-maven-plugin spring-releases https://repo.spring.io/libs-release spring-releases https://repo.spring.io/libs-release
其中这个dependency的作用是为SpringBoot应用提供操作MongoDB的功能:
org.springframework.boot spring-boot-starter-data-mongodb
这个dependent能让您的Spring Boot应用支持junit:
org.springframework.boot spring-boot-starter-test test
在src/main/test文件夹下创建一个以Tests结尾的.java文件,我的例子里是ApplicationTests.java:
将如下代码粘贴进去:
package main.test;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import main.java.library.Application;import main.java.library.Book;import main.java.library.BookRepository;@RunWith(SpringRunner.class)@SpringBootTest(classes=Application.class)public class ApplicationTests { @Autowired private BookRepository bookRepository; @Before public void setUp() { bookRepository.deleteAll(); } @Test public void test() throws Exception { bookRepository.save(new Book("1", "didi", "Jerry")); }}第27行代码,新建了一个Book对象,id为1,name为didi,作者为Jerry。然后通过bookRepository加入到MongoDB里。
BookRepository的实现:
import java.util.Optional;import org.springframework.data.mongodb.repository.MongoRepository;public interface BookRepository extends MongoRepository, BookRepositoryCustom { public Optional findByName(String name);}
这个JUnit单元测试运行成功后,
在MongoDB Compass里成功看到这条插入的记录:
上述就是小编为大家分享的Spring Boot中怎么操作MongoDB了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。
内容
成功
代码
文件
分析
应用
专业
中小
作用
作者
例子
内容丰富
功能
单元
对象
就是
文件夹
文章
更多
知识
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
wed网络安全讲解员于寒
中学网络安全建设方案
腾讯云数据库怎么用
qq三国如何服务器挂机
什么软件开发oa
江苏网络技术服务信息
广州市排水管网数据库
云服务器对网站
服务器任务怎么清理
甲状腺筛查数据库
山西服务器机柜厂家直销
智合云服务器跑路
ios软件开发培训中心
网络安全宣传周文案
软件开发方向职业分析
有关网站安全加固服务器
江苏服务器机柜哪种好
服务器安全配置基本知识
绝地求生各个服务器对比
鸡西软件开发平台
暑假不知道玩什么服务器
信阳网络技术推荐厂家
有关网络安全的会徽
为什么用户和服务器不兼容
2019软件开发企业排名
广州云梦互联网科技公司
ibm db2数据库下载
唐河app软件开发公司
网络安全攻防书籍雪域
查询各市平均人口数据库