本文演示SpringBoot整合MongoDB。
一、项目搭建
新建一个SpringBoot项目,引入依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
二、配置文件
配置项目端口号,添加数据库数据源配置信息:
server:
port: 8989
spring:
data:
mongodb:
uri: "mongodb://localhost:27017/test"
三、库表准备
使用MongoDB,新建test数据库及test文档,并插入记录:
四、编码实现
①创建实体类Student如下:
@Data
public class Student {
@MongoId
private String id;
private Long studentId;
private String name;
private Integer age;
}
②编写Controller类及测试请求方法:
@RestController
@RequestMapping("/")
public class MongoController {
@Autowired
MongoTemplate mongoTemplate;
@GetMapping("findAll")
public List<Student> findAll(){
return mongoTemplate.find(new Query(), Student.class, "test");
}
}
③启动类
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
④测试请求及响应:
测试验证OK。