【Java】SpringBoot快速整合mongoDB
在Spring Boot中快速整合MongoDB,你需要做以下几个步骤:
- 添加Maven依赖
- 配置application.properties或application.yml文件
- 创建实体类
- 创建MongoDB仓库接口
- 创建服务层和控制器层
以下是具体的代码示例:
1. Maven依赖(pom.xml)
<dependencies>
<!-- Spring Boot Starter Data MongoDB -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2. 配置文件(application.properties)
spring.data.mongodb.uri=mongodb://username:password@localhost:27017/your_database
或者使用YAML格式(application.yml):
spring:
data:
mongodb:
uri: mongodb://username:password@localhost:27017/your_database
3. 实体类(User.java)
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class User {
@Id
private String id;
private String name;
private int age;
// Getters and Setters
}
4. MongoDB仓库接口(UserRepository.java)
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepository extends MongoRepository<User, String> {
// 自定义查询方法(可选)
}
5. 服务层和控制器层
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.insert(user);
}
@GetMapping("/{id}")
public User getUserById(@PathVariable("id") String id) {
return userRepository.findById(id).orElse(null);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable("id") String id, @RequestBody User user) {
user.se
评论已关闭