目录
一、添加配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
二、配置yml
spring:
data:
mongodb:
uri: mongodb://localhost/stus
三、使用MongoTemplate对象
配置好以后,spring容器里就会有MongoTemplate对象,可直接注入使用,该对象对应的方法就是mongodb里对应的命令行名称。
package com.wxl.test;
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 java.util.List;
@SpringBootTest
class TestApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
@Test
void contextLoads() {
Person person=new Person();
mongoTemplate.save(person);
}
@Test
void contextLoads2() {
List<Person> personList= mongoTemplate.findAll(Person.class);
for(Person p: personList){
System.out.println(p);
}
}
class Person{
String name="Jack";
Integer age=12;
Boolean isMale=true;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", isMale=" + isMale +
'}';
}
}
}