映入依赖
<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地址 会自动创建
数据库
定义文档(文档相当于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(){ // 根据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(){ // 根据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(){ // 根据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); }
到此这篇关于mongodb 整合springboot举例介绍的文章就介绍到这了,更多相关mongodb 整合springboot内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论