目录
一、添加配置
二、配置yml
三、使用MongoTemplate对象
一、添加配置
org.springframework.boot
spring-boot-starter-data-mongodb
二、配置yml
spring:
data:
mongodb:
uri: mongodb://localhost/stus
三、使用MongoTemplate对象
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 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 +
'}';
}
}
}



