目录
1 创建模块
选nosql:spring data mangodb
或手动导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2 配置文件
spring:
data:
mongodb:
# 最后一个ssm_db是数据库的名字
uri: mongodb://localhost/ssm_db

3 使用MongoTemplate进行CRUD
package com.qing;
import com.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.gridfs.GridFsCriteria;
import java.util.List;
@SpringBootTest
class SpringbootMongoApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
//增
@Test
void testSave() {
Book book = new Book(2,"springboot学习手册", "工具书", "不会就翻书");
mongoTemplate.save(book);
}
//查所有
@Test
void testFind() {
List<Book> books = mongoTemplate.findAll(Book.class);
for (Book book:books) {
System.out.println(book);
}
}
//条件查询
@Test
void testFindBy() {
Book book = new Book();
book.setId(1);
Query query = new Query(Criteria.where("id").is(1)
.and("name").is("springboot学习手册"));
List<Book> books = mongoTemplate.find(query,Book.class);
for (Book book1:books) {
System.out.println(book1);
}
}
//删
@Test
void testRemove() {
Query query = new Query(Criteria.where("id").is(2));
mongoTemplate.remove(query,Book.class);
}
//改
@Test
void testUpdate() {
Query query = new Query(Criteria.where("name").is("springboot学习手册"));
Update update = new Update();
update.set("name","万能学习手册");
update.set("type","手册");
mongoTemplate.updateMulti(query,update,Book.class);
}
}
最后附上
package com.domain;
import lombok.Data;
@Data
public class Book {
private Integer id;
private String name;
private String type;
private String description;
public Book() {
}
public Book(Integer id, String name, String type, String description) {
this.id = id;
this.name = name;
this.type = type;
this.description = description;
}
public Book(String name, String type, String description) {
this.name = name;
this.type = type;
this.description = description;
}
}