一、安装MongoDB
sudo apt-get install mongodb
二、配置MongoDB
sudo service mongodb stop
mongod --bind_ip_all
三、springboot + MongoDB配置
- pom.xml配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
- application.properties配置
spring.data.mongodb.uri=mongodb://10.6.3.148:27017/mydb
四、springboot + MongoDB测试
@Repository
public interface StudentRepository extends MongoRepository<Student, String> {
}
public class AAApplicationTests {
@Autowired
private StudentRepository studentRepository;
private String id;
@Before
public void contextLoads() throws Exception {
Student student = new Student();
student.setName("kk_cock");
student.setAge(10);
studentRepository.save(student);
System.out.println(student.getId());
id = student.getId();
}
@Test
public void testGet() throws Exception {
Optional<Student> optional = studentRepository.findById(id);
if (optional.isPresent()) {
Student student = optional.get();
System.out.println(student.getName() + "," + student.getAge());
} else {
System.out.println("not found!");
}
}
}
输出内容:
2019-09-18-09:16:08 [main] INFO org.mongodb.driver.connection- Opened connection [connectionId{localValue:2, serverValue:15}] to 10.6.3.148:27017
5d81855883fa3544a0d97f82
kk_cock,10