MongoDB 整合SpringBoot舉例介紹
更新時間:2025年05月09日 11:06:04 作者:沒有感情的一匹碼
這篇文章主要介紹了MongoDB 整合SpringBoot的相關(guān)知識,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
映入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
yaml配置
spring: data: mongodb: uri: mongodb://localhost:27017/chat_memory_db # mongodb地址 會自動創(chuàng)建
數(shù)據(jù)庫
定義文檔(文檔相當(dāng)于MYSQL 的行)
定義文檔實體
@Data @AllArgsConstructor @NoArgsConstructor @Document("chat_message") public class ChatMessages { @Id private Long messageId; /** * 聊天記錄列表json字符串 */ private String content; }
@Test public void test(){ ChatMessages chatMessages = new ChatMessages(1L,"你好"); mongoTemplate.insert(chatMessages); }
增刪改查
public void testInsert(){ ChatMessages chatMessages = new ChatMessages(); chatMessages.setContent("你好"); mongoTemplate.insert(chatMessages); } @Test public void testQuery(){ ChatMessages byId = mongoTemplate.findById("680e38d1eb0e2f7b6d287541", ChatMessages.class); System.out.print(byId); } @Test public void testUpdate1(){ // 根據(jù)id修改 Criteria criteria = Criteria.where("_id").is("680e38d1eb0e2f7b6d287541"); Query query = new Query(criteria); Update update = new Update(); update.set("content","新的聊天記錄"); // 新增或者更新 mongoTemplate.upsert(query,update,ChatMessages.class); } @Test public void testUpdate2(){ // 根據(jù)id修改 Criteria criteria = Criteria.where("_id").is("100"); Query query = new Query(criteria); Update update = new Update(); update.set("content","新的聊天記錄"); // 新增或者更新 mongoTemplate.upsert(query,update,ChatMessages.class); } @Test public void testRemove(){ // 根據(jù)id修改 Criteria criteria = Criteria.where("_id").is("100"); Query query = new Query(criteria); Update update = new Update(); update.set("content","新的聊天記錄"); // 新增或者更新 mongoTemplate.remove(query,ChatMessages.class); }
到此這篇關(guān)于MongoDB 整合SpringBoot舉例介紹的文章就介紹到這了,更多相關(guān)MongoDB 整合SpringBoot內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中注解實現(xiàn)定時任務(wù)的兩種方式
這篇文章主要介紹了SpringBoot中注解實現(xiàn)定時任務(wù)的兩種方式,SpringBoot 定時任務(wù)是一種在SpringBoot應(yīng)用中自動執(zhí)行任務(wù)的機制,通過使用Spring框架提供的@Scheduled注解,我們可以輕松地創(chuàng)建定時任務(wù),需要的朋友可以參考下2023-10-10springboot 整合fluent mybatis的過程,看這篇夠了
這篇文章主要介紹了springboot 整合fluent mybatis的過程,配置數(shù)據(jù)庫連接創(chuàng)建數(shù)據(jù)庫的詳細(xì)代碼,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08SpringBoot?整合ChatGPT?API項目實戰(zhàn)教程
這篇文章主要介紹了SpringBoot整合ChatGPT API項目實戰(zhàn)教程,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05SpringBoot配置多數(shù)據(jù)源的四種方式分享
在日常開發(fā)中我們都是以單個數(shù)據(jù)庫進(jìn)行開發(fā),在小型項目中是完全能夠滿足需求的,但是,當(dāng)我們牽扯到大型項目的時候,單個數(shù)據(jù)庫就難以承受用戶的CRUD操作,那么此時,我們就需要使用多個數(shù)據(jù)源進(jìn)行讀寫分離的操作,本文就給大家介紹SpringBoot配置多數(shù)據(jù)源的方式2023-07-07