在IDEA下的MongoDB项目搭建过程,实现增删查改,springboot+MongoDB
以下是使用Spring Boot和MongoDB的一个简单示例,包括增删查改操作:
- 在
pom.xml
中添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
以连接到MongoDB:
spring.data.mongodb.uri=mongodb://localhost:27017/your_database
- 创建一个实体类:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class YourEntity {
@Id
private String id;
private String name;
// 省略getter和setter
}
- 创建一个MongoDB仓库接口:
import org.springframework.data.mongodb.repository.MongoRepository;
public interface YourEntityRepository extends MongoRepository<YourEntity, String> {
}
- 创建一个服务类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class YourEntityService {
@Autowired
private YourEntityRepository repository;
public List<YourEntity> findAll() {
return repository.findAll();
}
public Optional<YourEntity> findById(String id) {
return repository.findById(id);
}
public YourEntity save(YourEntity entity) {
return repository.save(entity);
}
public void deleteById(String id) {
repository.deleteById(id);
}
}
- 创建一个控制器类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/your-entities")
public class YourEntityController {
@Autowired
private YourEntityService service;
@GetMapping
public List<YourEntity> getAll() {
return service.findAll();
}
@GetMapping("/{id}")
public Optional<YourEntity> getById(@PathVariable String id) {
return service.findById(id);
}
@PostMapping
public YourEntity create(@RequestBody YourEntity entity) {
return service.save(ent
评论已关闭