springboot如何整合mongodb
时间: 2023-12-13 08:34:34 浏览: 81
springboot整合mongodb changestream代码
5星 · 资源好评率100%
在Spring Boot中,我们可以使用spring-boot-starter-data-mongodb依赖来整合MongoDB。下面是整合MongoDB的步骤:
1.在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
```
2.在application.properties文件中添加MongoDB的配置信息:
```properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydb
```
3.创建一个MongoDB的Repository接口,继承MongoRepository:
```java
@Repository
public interface UserRepository extends MongoRepository<User, String> {
User findByUsername(String username);
}
```
4.在Service中注入该Repository,并使用其提供的方法进行增删查改操作:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
public void saveUser(User user) {
userRepository.save(user);
}
@Override
public void deleteUser(String id) {
userRepository.deleteById(id);
}
@Override
public List<User> findAllUsers() {
return userRepository.findAll();
}
}
```
阅读全文